Swift中鲜为人知的特性:运算符号(Swift必懂的)

1,442 阅读2分钟

Swift运算符中的~=算不上出名,很多人并不清楚它是做什么的,该如何运用。简而言之,使用这个运算符,可以查看一个范围是否包含某个值。

本文将通过一些例子,带你了解这个运算符的用处和用法。开始吧!

考虑这样一种常见情况:在没有遇到任何错误的情况下,要启动网络请求并打出数据,因此要创建一个URLSessionDataTask,如下所示:

let task = URLSession.shared.dataTask(with: URL(string: "https://google.com")!) { (data,response, error) in
                                  guardlet data = data,
                                      let response = response as? HTTPURLResponse, (200..<300) ~=response.statusCode else {
                                          iflet error = error {
                                            print(error)
                                          } else {
                                             print("Somethingwent wrong")
                                          }
                                          return
                                  }
                                        print("Received data: \(data)")
                              }

上述代码中就使用了~=,以检查状态码整数值是否在200到300之间(不包括两极),如果是,则结果是成功的。否则,将输出一条错误消息。

更改print语句并启动任务,实际上会得到有效响应,状态码是200:

let task = URLSession.shared.dataTask(with: URL(string: "https://google.com")!) { (data,response, error) in
                                 guardlet data = data,
                                      let response = response as? HTTPURLResponse, (200..<300) ~=response.statusCode else {
                                          iflet error = error {
                                            print(error)
                                          } else {
                                             print("Somethingwent wrong")
                                          }
                                          return
                                  }
                                        print("Received data: \(data), status code: \(response.statusCode)")
                              }
             task.resume()

Swift鲜为人知的特性:~=运算符是什么? 代码在一个Xcode Playground中运行

再来看看另一个在后台使用~=运算符的例子。假设有一个简单的Coordinate结构并将其实例化:

structCoordinate {
              let value: (latitude:CLLocationDegrees, longitude: CLLocationDegrees)
          }
             let coordinate =Coordinate(
              value: (
                  latitude: 40.7128,
                  longitude: 74.0060
              )
          )

使用switch语句,查看这个坐标是否在纽约市的坐标范围内(该实例被简化):

switch coordinate.value {
               case (40...41, 73...76):
                   print("Hmm... seems like we found NewYork City")
               default:
                   print("Unknown coordinates")
               }

指定纬度值和经度值的范围。在后台,~=运算符使用==运算符将范围内的每个值与coordinate的值进行比较:

Swift鲜为人知的特性:~=运算符是什么? Swift鲜为人知的特性还有很多,比如值绑定模式、vDSP框架、CustomStringConvertible协议、类和静态的区别等等。这些概念你都明白嘛?如果不了解的话,赶快去查漏补缺吧。