嗨,我最近在开发过程中遇到了一个奇怪的问题。本机包含无法正常工作。下面是我的代码。
struct Hello {
var name : String = ""
var address: String = ""
var phone : String = ""
init(name: String,address: String,phone: String) {
self.name = name
self.address = address
self.phone = phone
}
}
struct Buddy {
var phone : String = ""
var name: String = ""
var address: String = ""
init(name: String,address: String,phone: String) {
self.name = name
self.address = address
self.phone = phone
}
}
var a: [Hello] = []
a.append(Hello(name: "Gaurav", address: "Address1", phone: "123456"))
a.append(Hello(name: "Kumar", address: "Address2", phone: "123457"))
a.append(Hello(name: "Singh", address: "Address3", phone: "123"))
var b: Buddy = Buddy(name: "Pawan", address: "Address1", phone: "123")
if (a.contains(where: { $0.phone != b.phone})) {
print("doest not contain")
} else {
print(" contain")
}
实际结果: 打印(“不包含”)
预期结果: print(“包含”)
答案 0 :(得分:0)
代码正确。
您正在检查
a
是否包含一个Hello
,其电话号码为不是 123。
这是true
,因为甚至有两个项目的电话号码不同
答案 1 :(得分:0)
将最后一部分更改为:
if (a.contains(where: { $0.phone == b.phone})) {
print("contains")
} else {
print("does not contain")
}
,它将返回正确的值。