Compare arrays in swift

前端 未结 6 1229
死守一世寂寞
死守一世寂寞 2020-11-30 02:59

Trying to understand how swift compares arrays.

var myArray1 : [String] = [\"1\",\"2\",\"3\",\"4\",\"5\"]
var myArray2 : [String] = [\"1\",\"2\",\"3\",\"4\",         


        
6条回答
  •  感动是毒
    2020-11-30 03:38

    If you have an array of custom objects, one has to be careful with the equality test, at least with Swift 4.1:
    If the custom object is not a subclass of NSObject, the comparison uses the static func == (lhs: Nsobject, rhs: Nsobject) -> Bool, which has to be defined.
    If it is a subclass of NSObject, it uses the func isEqual(_ object: Any?) -> Bool, which has to be overridden.

    Please check the following code, and set breakpoints at all return statements.

    class Object: Equatable {
    
        static func == (lhs: Object, rhs: Object) -> Bool {
            return true
        }
    }
    

    The following class inheritates Equatable from NSObject

    class Nsobject: NSObject {
    
        static func == (lhs: Nsobject, rhs: Nsobject) -> Bool {
            return true
        }
    
    
        override func isEqual(_ object: Any?) -> Bool {
            return true
        }
    
    }  
    

    They can be compared with:

    let nsObject1 = Nsobject()
    let nsObject2 = Nsobject()
    let nsObjectArray1 = [nsObject1]
    let nsObjectArray2 = [nsObject2]
    let _ = nsObjectArray1 == nsObjectArray2
    
    let object1 = Object()
    let object2 = Object()
    let objectArray1 = [object1]
    let objectArray2 = [object2]
    let _ = objectArray1 == objectArray2
    

提交回复
热议问题