How to check if an element is in an array

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

    I used filter.

    let results = elements.filter { el in el == 5 }
    if results.count > 0 {
        // any matching items are in results
    } else {
        // not found
    }
    

    If you want, you can compress that to

    if elements.filter({ el in el == 5 }).count > 0 {
    }
    

    Hope that helps.


    Update for Swift 2

    Hurray for default implementations!

    if elements.contains(5) {
        // any matching items are in results
    } else {
        // not found
    }
    

提交回复
热议问题