How to check if an element is in an array

后端 未结 17 1192
囚心锁ツ
囚心锁ツ 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 10:48

    For those who came here looking for a find and remove an object from an array:

    Swift 1

    if let index = find(itemList, item) {
        itemList.removeAtIndex(index)
    }
    

    Swift 2

    if let index = itemList.indexOf(item) {
        itemList.removeAtIndex(index)
    }
    

    Swift 3, 4

    if let index = itemList.index(of: item) {
        itemList.remove(at: index)
    }
    

    Swift 5.2

    if let index = itemList.firstIndex(of: item) {
        itemList.remove(at: index)
    }
    

提交回复
热议问题