简体   繁体   English

〜= Swift中的运算符

[英]~= operator in Swift

I recently downloaded the Advanced NSOperations sample app from Apple and found this code... 我最近从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
}

It seems to use the ~= operator against Strings and Ints but I've never seen it before. 它似乎对StringsInts使用~=运算符,但我从未见过。

What is it? 它是什么?

It is an operator used for pattern matching in a case statement. 它是用于case语句中的模式匹配的运算符。

You can take a look here to know how you can use and leverage it providing your own implementation: 您可以在这里了解如何使用和利用它来提供自己的实现:

Here is a simple example of defining a custom one and using it: 这是定义和使用自定义变量的简单示例:

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!"

Simply use a shortcut to "range": you can construct a range and "~=" means "contains". 只需使用快捷方式“范围”:您可以构造一个范围,“〜=”表示“包含”。 (other can add more theoretical details, but the sense is this). (其他可以添加更多理论细节,但意义是这样)。 Read it as "contains" 读为“包含”

let n: Int = 100

// verify if n is in a range, say: 10 to 100 (included)

if n>=10 && n<=100 {
    print("inside!")
}

// using "patterns"
if 10...100 ~= n {
    print("inside! (using patterns)")

}

try with some values of n. 尝试使用某些n值。

Is used widely for example in HTTP response: 例如在HTTP响应中被广泛使用:

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

You can look into Define Swift 您可以查看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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM