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

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

偶然的你
TA貢獻1841條經驗 獲得超3個贊
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貢獻1797條經驗 獲得超6個贊
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 關注
- 809 瀏覽
添加回答
舉報
0/150
提交
取消