Nui*_*ibb 40 properties contains swift
我试图检查一个对象数组中是否存在特定项(属性的值),但无法找到任何解决方案.请让我知道,我在这里失踪了什么.
class Name {
var id : Int
var name : String
init(id:Int, name:String){
self.id = id
self.name = name
}
}
var objarray = [Name]()
objarray.append(Name(id: 1, name: "Nuibb"))
objarray.append(Name(id: 2, name: "Smith"))
objarray.append(Name(id: 3, name: "Pollock"))
objarray.append(Name(id: 4, name: "James"))
objarray.append(Name(id: 5, name: "Farni"))
objarray.append(Name(id: 6, name: "Kuni"))
if contains(objarray["id"], 1) {
println("1 exists in the array")
}else{
println("1 does not exists in the array")
}
Run Code Online (Sandbox Code Playgroud)
Ant*_*nio 63
您可以像这样过滤数组:
let results = objarray.filter { $0.id == 1 }
Run Code Online (Sandbox Code Playgroud)
这将返回一个与闭包中指定的条件匹配的元素数组 - 在上面的例子中,它将返回一个包含id属性等于1的所有元素的数组.
由于您需要布尔结果,只需执行以下检查:
let exists = results.isEmpty == false
Run Code Online (Sandbox Code Playgroud)
exists 如果过滤后的数组至少有一个元素,则为true
The*_*Eye 15
在Swift 3中:
if objarray.contains(where: { name in name.id == 1 }) {
print("1 exists in the array")
} else {
print("1 does not exists in the array")
}
Run Code Online (Sandbox Code Playgroud)
在Swift 2.x中:
if objarray.contains({ name in name.id == 1 }) {
print("1 exists in the array")
} else {
print("1 does not exists in the array")
}
Run Code Online (Sandbox Code Playgroud)
小智 7
//斯威夫特4.2
if objarray.contains(where: { $0.id == 1 }) {
// print("1 exists in the array")
} else {
// print("1 does not exists in the array")
}
Run Code Online (Sandbox Code Playgroud)
这里主要有两个可行的选择。
contains(where:上的方法objarray。我只是对 @TheEye 的答案做了一个小小的修改:if objarray.contains(where: { $0.id == 1 }) {
print("1 exists in the array")
} else {
print("1 does not exists in the array")
}
Run Code Online (Sandbox Code Playgroud)
Equatable协议一致性要求并仅使用contains,如下所示:// first conform `Name` to `Equatable`
extension Name: Equatable {
static func == (lhs: Name, rhs: Name) -> Bool {
lhs.id == rhs.id
}
}
// then
let firstName = Name(id: 1, name: "Different Name")
if objarray.contains(firstName) {
print("1 exists in the array") // prints this out although the names are different, because of the override
} else {
print("1 does not exists in the array")
}
Run Code Online (Sandbox Code Playgroud)