2017-02-25 44 views
1

我想检查是否在数组中存在的一个项目:斯威夫特3:在数组中检查项目

protocol Item { 
     var name: String! {get set} 
     var value: Int! {get set} 
    } 

class UserList { 
    var items: [Item]! 

    func checkItem(item: Item) -> Bool{ 
     if items.contains(where: {$0 === item}) { // Error 
      return true 
     } 
     return false 
    } 
} 

我得到这个错误:

Binary operator '===' cannot be applied to two 'Item' operands 

回答

1

如果你真的想用身份运算符(===)为您checkItem,你可以宣布你的Item为一类协议:

protocol Item: class { 
    var name: String! {get set} 
    var value: Int! {get set} 
} 

class UserList { 
    var items: [Item]! 

    func checkItem(item: Item) -> Bool{ 
     return items.contains {$0 === item} 
    } 
} 

(我不明白你为什么需要隐式展开选项,所以我一直在那里。不过,我自己绝不会用这么多IUOs)


但不知身份是你想要什么:

class ClassItem: Item { 
    var name: String! 
    var value: Int! 

    init(_ name: String, _ value: Int) { 
     self.name = name 
     self.value = value 
    } 
} 
let myList = UserList() 
myList.items = [ClassItem("aaa", 1), ClassItem("bbb", 2)] 
var result = myList.checkItem(item: ClassItem("aaa", 1)) 
print(result) //->false 

如果结果false是不是你所期望的,你需要定义你自己等于Item并用它定义你的checkItem(item:)

0

我一直用这个简单的解决方案,即来自objecitve-C

let array = ["a,b"] 
if let _ = array.index(of: "b") 
{ 
    //if "b" is in array   
} 
else 
{ 
    //if "b" is not in aray 
}