〜=运算符在Swift中

我最近从苹果下载了高级NSOperations示例应用程序,发现这个代码…

// Operators to use in the switch statement. private func ~=(lhs: (String, Int, String?), rhs: (String, Int, String?)) -> Bool { return lhs.0 ~= rhs.0 && lhs.1 ~= rhs.1 && lhs.2 == rhs.2 } private func ~=(lhs: (String, OperationErrorCode, String), rhs: (String, Int, String?)) -> Bool { return lhs.0 ~= rhs.0 && lhs.1.rawValue ~= rhs.1 && lhs.2 == rhs.2 } 

它似乎使用~=运算符反对StringsInts但我从来没有见过它。

它是什么?

它是一个在case语句中用于模式匹配的操作符。

你可以看看这里,知道如何使用和利用它提供自己的实现:

下面是定义一个自定义的一个简单的例子,并使用它:

 struct Person { let name : String } // Function that should return true if value matches against pattern func ~=(pattern: String, value: Person) -> Bool { return value.name == pattern } let p = Person(name: "Alessandro") switch p { // This will call our custom ~= implementation, all done through type inference case "Alessandro": print("Hey it's me!") default: print("Not me") } // Output: "Hey it's me!" if case "Alessandro" = p { print("It's still me!") } // Output: "It's still me!" 

你可以看看Define Swift

 func ~=<I : IntervalType>(pattern: I, value: I.Bound) -> Bool func ~=<T>(lhs: _OptionalNilComparisonType, rhs: T?) -> Bool func ~=<T : Equatable>(a: T, b: T) -> Bool func ~=<I : ForwardIndexType where I : Comparable>(pattern: Range<I>, value: I) -> Bool 

只需使用一个快捷方式范围,你可以构造一个范围和“〜=”包含。 (其他可以添加更多的理论细节,但感觉是这样)。 阅读它作为“包含”

 let n: Int = 100 // verify if n is a range, sat: 10 to 100 (included) if n>=10 && n<=100{ print("inside!") } // using "patterns" if 10...100 ~= n{ print("inside! (using patterns)") } 

尝试一些n的值。

在HTTP响应中被广泛使用:

 if let response = response as? HTTPURLResponse , 200...299 ~= response.statusCode { let contentLength : Int64 = response.expectedContentLength completionHandler(contentLength) } else { completionHandler(nil)