Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
145 views
in Technique[技术] by (71.8m points)

ios - ~= operator in Swift

I recently downloaded the Advanced NSOperations sample app from Apple and found this code...

// 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.

What is it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

Is used widely for example in HTTP response:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...