How to check if an element is in an array

后端 未结 17 1189
囚心锁ツ
囚心锁ツ 2020-11-22 10:24

In Swift, how can I check if an element exists in an array? Xcode does not have any suggestions for contain, include, or has, and a qu

17条回答
  •  无人共我
    2020-11-22 11:11

    Swift 4.2 +
    You can easily verify your instance is an array or not by the following function.

    func verifyIsObjectOfAnArray(_ object: T) -> Bool {
       if let _ = object as? [T] {
          return true
       }
    
       return false
    }
    

    Even you can access it as follows. You will receive nil if the object wouldn't be an array.

    func verifyIsObjectOfAnArray(_ object: T) -> [T]? {
       if let array = object as? [T] {
          return array
       }
    
       return nil
    }
    

提交回复
热议问题