~=SWIFT中的运算符

cigdeys3  于 2022-09-19  发布在  Swift
关注(0)|答案(3)|浏览(196)

我最近从苹果下载了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使用了~=运算符,但我以前从未见过它。

那是什么?

amrnrhlw

amrnrhlw1#

只需将其用作“Range”的快捷方式:您可以构造一个Range,而“~=”表示“包含”。(其他人可以添加更多理论细节,但意义是这样的)。读作“包含”

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

}

尝试使用一些n的值。

被广泛使用,例如在HTTP响应中:

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

kknvjkwl2#

它是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!"
fjnneemd

fjnneemd3#

您可以查看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

相关问题