如何检查元素是否在数组中在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()SequenceTypeEquatable
备注:
这,这个 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
containsArray
let a = [ 1, 2, 3, 4 ]a.contains(2) // => true, only usable if Element : Equatable
a.contains { $0 < 1 } // => false- 3 回答
- 0 关注
- 842 浏览
添加回答
举报
0/150
提交
取消
