how to compare two optional NSArrays in Swift

后端 未结 4 1251
野的像风
野的像风 2020-12-18 17:49

Let\'s have two optional NSArrays. The goal is to check, if they are equal. My solution is

func isArrayEqualToArray(array1:NSArray?, array2:NSArray?) -> B         


        
4条回答
  •  猫巷女王i
    2020-12-18 18:10

    It is quite simple:

    func isArrayEqualToArray(array1: NSArray?, array2: NSArray?) -> Bool {
        return array1 == array2
    }
    

    does exactly what you want.

    Why does it work? Here == is the operator that compares optionals

    func ==(lhs: T?, rhs: T?) -> Bool
    

    and that gives true if both operands are nil, or of both operands are non-nil and the unwrapped operands are equal.

    Also NSArray inherits from NSObject which conforms to Equatable, and comparing NSObjects with == uses the isEqual: method, which is implemented as isEqualToArray: on NSArray. Therefore

    array1 == array2
    

    gives the same result as

    array1.isEqualToArray(array2)
    

提交回复
热议问题