How to check if an element is in an array

后端 未结 17 983
囚心锁ツ
囚心锁ツ 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:06

    Array

    let elements = [1, 2, 3, 4, 5, 5]
    

    Check elements presence

    elements.contains(5) // true
    

    Get elements index

    elements.firstIndex(of: 5) // 4
    elements.firstIndex(of: 10) // nil
    

    Get element count

    let results = elements.filter { element in element == 5 }
    results.count // 2
    

提交回复
热议问题