本文翻译自: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)
}