〜= 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
}

使用することを思わ~=に対してオペレータをStringsしてIntsますが、私は前にそれを見たことがありません。

それは何ですか?

アレッサンドロ・オッロ:

これは、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!"

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事