在Swift中,我如何检查数组中是否存在一个元素?Xcode并没有给出包含、包含或拥有的建议,快速搜索这本书也一无所获。知道怎么检查这个吗?我知道有一个方法找到返回索引号,但是否有一个方法返回一个布尔像ruby的#include??
我需要的例子:
var elements = [1,2,3,4,5]
if elements.contains(5) {
//do something
}
在Swift中,我如何检查数组中是否存在一个元素?Xcode并没有给出包含、包含或拥有的建议,快速搜索这本书也一无所获。知道怎么检查这个吗?我知道有一个方法找到返回索引号,但是否有一个方法返回一个布尔像ruby的#include??
我需要的例子:
var elements = [1,2,3,4,5]
if elements.contains(5) {
//do something
}
当前回答
以防有人试图找到一个indexPath是否在选定的(如在UICollectionView或UITableView cellForItemAtIndexPath函数):
var isSelectedItem = false
if let selectedIndexPaths = collectionView.indexPathsForSelectedItems() as? [NSIndexPath]{
if contains(selectedIndexPaths, indexPath) {
isSelectedItem = true
}
}
其他回答
以防有人试图找到一个indexPath是否在选定的(如在UICollectionView或UITableView cellForItemAtIndexPath函数):
var isSelectedItem = false
if let selectedIndexPaths = collectionView.indexPathsForSelectedItems() as? [NSIndexPath]{
if contains(selectedIndexPaths, indexPath) {
isSelectedItem = true
}
}
对于那些来这里寻找从数组中查找并移除对象的人:
斯威夫特1
if let index = find(itemList, item) {
itemList.removeAtIndex(index)
}
斯威夫特2
if let index = itemList.indexOf(item) {
itemList.removeAtIndex(index)
}
Swift 3,4
if let index = itemList.index(of: item) {
itemList.remove(at: index)
}
斯威夫特5.2
if let index = itemList.firstIndex(of: item) {
itemList.remove(at: index)
}
数组
let elements = [1, 2, 3, 4, 5, 5]
检查元素是否存在
elements.contains(5) // true
获取元素索引
elements.firstIndex(of: 5) // 4
elements.firstIndex(of: 10) // nil
获取元素计数
let results = elements.filter { element in element == 5 }
results.count // 2
Swift 4.2 + 通过下面的函数,可以很容易地验证实例是否是数组。
func verifyIsObjectOfAnArray<T>(_ object: T) -> Bool {
if let _ = object as? [T] {
return true
}
return false
}
甚至你也可以像下面这样访问它。如果对象不是数组,你将收到nil。
func verifyIsObjectOfAnArray<T>(_ object: T) -> [T]? {
if let array = object as? [T] {
return array
}
return nil
}
在Swift 2.1中,nsarray有containsobject,可以像这样使用:
if myArray.containsObject(objectImCheckingFor){
//myArray has the objectImCheckingFor
}