如何检查元素是否在数组中

本文翻译自: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)
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值