Swift Equatable Protocol

前端 未结 3 1047
南方客
南方客 2020-11-29 06:24

I was folling this tutorial for Swift: https://www.raywenderlich.com/125311/make-game-like-candy-crush-spritekit-swift-part-1 and came across this code:

func          


        
相关标签:
3条回答
  • 2020-11-29 06:43

    Move this function

    func == (lhs: Cookie, rhs: Cookie) -> Bool {
        return lhs.column == rhs.column && lhs.row == rhs.row
    }
    

    Outside of the cookie class. It makes sense this way since it's overriding the == operator at the global scope when it is used on two Cookies.

    0 讨论(0)
  • 2020-11-29 06:49

    making the class an NSObject solved the equatable problems for me...

    class Cookie: NSObject {
    ...
    }
    

    (got the tip from the iOS apprentice tutorials)

    0 讨论(0)
  • 2020-11-29 06:56

    SWIFT 2:

    As in swift 2 NSObject already conforms to Equatable.You don't need conformance at the top so it's like

    class Cookie: NSObject {
        ...
    
    }
    

    And you need to override isEqual method as

    class Cookie:NSObject{
        var column: Int
        var row: Int
    
        //..........
    
        override func isEqual(object: AnyObject?) -> Bool {
            guard let rhs = object as? Cookie else {
                return false
            }
            let lhs = self
    
            return lhs.column == rhs.column
        }
    
    }
    

    This time isEqual method is inside the class. :)

    EDIT for SWIFT 3: Change this method as

    override func isEqual(_ object: AnyObject?) -> Bool {
            guard let rhs = object as? Cookie else {
                return false
            }
            let lhs = self
    
            return lhs.column == rhs.column
        }
    
    0 讨论(0)
提交回复
热议问题