0

Hi I just recently faced a weird problem during my development.native contains not working properly.Below is my Code.

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")
}

Actual result: print("doest not contain")

Expected Result: print("contain")

2 Answers2

0

The code is correct.

You are checking

Does a contain a Hello whose phone number is not 123.

This is true because there are even two items with a different phone number

vadian
  • 274,689
  • 30
  • 353
  • 361
0

Change the last part to:

if (a.contains(where: { $0.phone == b.phone})) {
    print("contains")
} else {
    print("does not contain")
}

and it will return the proper value.

valosip
  • 3,167
  • 1
  • 14
  • 26