如何檢查元素是否在數(shù)組中在SWIFT中,如何檢查數(shù)組中是否存在一個(gè)元素?Xcode沒有任何建議contain, include,或has,快速翻閱這本書,什么也沒有發(fā)現(xiàn)。知道怎么查這個(gè)嗎?我知道有一種方法find返回索引號(hào),但是否存在返回布爾值(如ruby‘s)的方法?#include??我需要的例子:var elements = [1,2,3,4,5]if elements.contains(5) {
//do something}
3 回答

GCT1015
TA貢獻(xiàn)1827條經(jīng)驗(yàn) 獲得超4個(gè)贊
斯威夫特2,3,4,5:
let elements = [1, 2, 3, 4, 5]if elements.contains(5) { print("yes")}
contains()
SequenceType
Equatable
備注:
這,這個(gè) contains()
方法要求序列元素采用 Equatable
協(xié)議,比較。 如果序列元素是 NSObject
子類,則必須重寫 isEqual:
,見 還有另一個(gè)-更一般的- contains()
方法,該方法不要求元素相等,并以謂詞作為參數(shù),請(qǐng)參見。
SWIFT舊版本:
let elements = [1,2,3,4,5]if contains(elements, 5) { println("yes")}

偶然的你
TA貢獻(xiàn)1841條經(jīng)驗(yàn) 獲得超3個(gè)贊
SWIFT 1
if let index = find(itemList, item) { itemList.removeAtIndex(index)}
SWIFT 2
if let index = itemList.indexOf(item) { itemList.removeAtIndex(index)}
SWIFT 3,4,5
if let index = itemList.index(of: item) { itemList.remove(at: index)}

互換的青春
TA貢獻(xiàn)1797條經(jīng)驗(yàn) 獲得超6個(gè)贊
extension Array { func contains<T where T : Equatable>(obj: T) -> Bool { return self.filter({$0 as? T == obj}).count > 0 }}
array.contains(1)
更新SWIFT 2/3
contains
Array
let a = [ 1, 2, 3, 4 ]a.contains(2) // => true, only usable if Element : Equatable a.contains { $0 < 1 } // => false
- 3 回答
- 0 關(guān)注
- 802 瀏覽
添加回答
舉報(bào)
0/150
提交
取消