如何檢查元素是否在數組中

本文翻譯自:How to check if an element is in an array

In Swift, how can I check if an element exists in an array? 在Swift中,如何檢查數組中是否存在元素? Xcode does not have any suggestions for contain , include , or has , and a quick search through the book turned up nothing. Xcode沒有對containincludehas任何建議,並且快速搜索本書不會發現任何建議。 Any idea how to check for this? 知道如何檢查嗎? I know that there is a method find that returns the index number, but is there a method that returns a boolean like ruby's #include? 我知道有find返回索引號的方法的方法,但是有沒有方法返回像ruby的#include?這樣的布爾值的方法#include? ?

Example of what I need: 我需要的示例:

var elements = [1,2,3,4,5]
if elements.contains(5) {
  //do something
}

#1樓

參考:https://stackoom.com/question/1d82K/如何檢查元素是否在數組中


#2樓

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 Swift 2更新

Hurray for default implementations! 歡呼使用默認實現!

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

#3樓

Use this extension: 使用此擴展名:

extension Array {
    func contains<T where T : Equatable>(obj: T) -> Bool {
        return self.filter({$0 as? T == obj}).count > 0
    }
}

Use as: 用於:

array.contains(1)

Updated for Swift 2/3 已針對Swift 2/3更新

Note that as of Swift 3 (or even 2), the extension is no longer necessary as the global contains function has been made into a pair of extension method on Array , which allow you to do either of: 請注意,從Swift 3(甚至2)開始,不再需要擴展,因爲已將全局contains函數做成Array上的一對擴展方法,您可以執行以下任一操作:

let a = [ 1, 2, 3, 4 ]

a.contains(2)           // => true, only usable if Element : Equatable

a.contains { $0 < 1 }   // => false

#4樓

Swift 2, 3, 4, 5: 斯威夫特2、3、4、5:

let elements = [1, 2, 3, 4, 5]
if elements.contains(5) {
    print("yes")
}

contains() is a protocol extension method of SequenceType (for sequences of Equatable elements) and not a global method as in earlier releases. contains()SequenceType協議擴展方法 (適用於Equatable元素的序列),而不是早期版本中的全局方法。

Remarks: 備註:

Swift older versions: Swift舊版本:

let elements = [1,2,3,4,5]
if contains(elements, 5) {
    println("yes")
}

#5樓

Just in case anybody is trying to find if an indexPath is among the selected ones (like in a UICollectionView or UITableView cellForItemAtIndexPath functions): 以防萬一有人試圖查找indexPath是否在所選indexPath中(例如,在UICollectionViewUITableView cellForItemAtIndexPath函數中):

    var isSelectedItem = false
    if let selectedIndexPaths = collectionView.indexPathsForSelectedItems() as? [NSIndexPath]{
        if contains(selectedIndexPaths, indexPath) {
            isSelectedItem = true
        }
    }

#6樓

For those who came here looking for a find and remove an object from an array: 對於那些來這裏尋找並從數組中刪除對象的人:

Swift 1 斯威夫特1

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

Swift 2 迅捷2

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

Swift 3, 4, 5 斯威夫特3,4,5

if let index = itemList.index(of: item) {
    itemList.remove(at: index)
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章