How to check if an element is in an array

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

    The simplest way to accomplish this is to use filter on the array.

    let result = elements.filter { $0==5 }
    

    result will have the found element if it exists and will be empty if the element does not exist. So simply checking if result is empty will tell you whether the element exists in the array. I would use the following:

    if result.isEmpty {
        // element does not exist in array
    } else {
        // element exists
    }
    

提交回复
热议问题