我最近从Apple 下载了 Advanced 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 }
似乎使用了~=运算符来代替Strings,Ints但我从未见过。
~=
Strings
Ints
它是什么?
它是用于case语句中模式匹配的运算符。
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!"