Check whether an object is an NSArray or NSDictionary

前端 未结 4 620
慢半拍i
慢半拍i 2021-02-01 13:28

As per subject, how can I check whether an object is an NSArray or NSDictionary?

4条回答
  •  南方客
    南方客 (楼主)
    2021-02-01 13:59

    Just in case anyone comes late to this party looking for a Swift equivalent, here you go. It's a lot more elegant than the Objective-C version, IMHO, because not only does it check the types, but it casts them to the desired type at the same time:

    if let arrayVersion = obj as? NSArray {
        // arrayVersion is guaranteed to be a non-`nil` NSArray
    } else if let dictionaryVersion = obj as? NSDictionary {
        // dictionaryVersion is guaranteed to be a non-`nil` NSDictionary
    } else {
        // it's neither
    }
    

提交回复
热议问题