在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
}
当前回答
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
}
其他回答
最简单的方法是在数组上使用过滤器。
let result = elements.filter { $0==5 }
如果元素存在,结果将显示已找到的元素;如果元素不存在,结果将为空。因此,简单地检查result是否为空将告诉您元素是否存在于数组中。我会使用以下方法:
if result.isEmpty {
// element does not exist in array
} else {
// element exists
}
在Swift 2.1中,nsarray有containsobject,可以像这样使用:
if myArray.containsObject(objectImCheckingFor){
//myArray has the objectImCheckingFor
}
包含等于的属性的数组
yourArray.contains(where: {$0.propertyToCheck == value })
返回布尔值。
如果用户发现特定的数组元素,则使用以下代码相同的整数值。
var arrelemnts = ["sachin", "test", "test1", "test3"]
if arrelemnts.contains("test"){
print("found") }else{
print("not found") }
对于那些来这里寻找从数组中查找并移除对象的人:
斯威夫特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)
}