本文翻譯自: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沒有對contain
, include
或has
任何建議,並且快速搜索本書不會發現任何建議。 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: 備註:
- This
contains()
method requires that the sequence elements adopt theEquatable
protocol, compare eg Andrews's answer . 這個contains()
方法要求序列元素採用Equatable
協議,例如比較Andrews的answer 。 - If the sequence elements are instances of a
NSObject
subclass then you have to overrideisEqual:
, see NSObject subclass in Swift: hash vs hashValue, isEqual vs == . 如果序列元素是NSObject
子類的實例,則必須重寫isEqual:
:,請參見Swift中的NSObject子類:hash vs hashValue,isEqual vs == 。 - There is another – more general –
contains()
method which does not require the elements to be equatable and takes a predicate as an argument, see eg Shorthand to test if an object exists in an array for Swift? 還有另一個(更通用的)contains()
方法不需要元素是相等的,並且需要謂詞作爲參數,請參見例如速記來測試對象是否存在於Swift數組中? . 。
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
中(例如,在UICollectionView
或UITableView
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)
}