~= operator in Swift

后端 未结 3 1963
悲哀的现实
悲哀的现实 2020-12-04 14:10

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

// Operators to use in the switch statement.
pr         


        
相关标签:
3条回答
  • 2020-12-04 14:47

    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)
    
    0 讨论(0)
  • 2020-12-04 14:55

    It is an operator used for pattern matching in a case statement.

    You can take a look here to know how you can use and leverage it providing your own implementation:

    • http://oleb.net/blog/2015/09/swift-pattern-matching/
    • http://austinzheng.com/2014/12/17/custom-pattern-matching/

    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!"
    
    0 讨论(0)
  • 2020-12-04 14:57

    You can look into 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
    
    0 讨论(0)
提交回复
热议问题