一尘不染

〜= Swift中的运算符

swift

我最近从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
}

似乎使用了~=运算符来代替StringsInts但我从未见过。

它是什么?


阅读 190

收藏
2020-07-07

共1个答案

一尘不染

它是用于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!"
2020-07-07