how to check if a property value exists in array of objects in swift

SwiftPropertiesContains

Swift Problem Overview


I am trying to check if a specific item (value of a property) exists in a array of objects, but could not find out any solution. Please let me know, what i am missing here.

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

Swift Solutions


Solution 1 - Swift

You can filter the array like this:

let results = objarray.filter { $0.id == 1 }

that will return an array of elements matching the condition specified in the closure - in the above case, it will return an array containing all elements having the id property equal to 1.

Since you need a boolean result, just do a check like:

let exists = results.isEmpty == false

exists will be true if the filtered array has at least one element

Solution 2 - Swift

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

Solution 3 - Swift

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

Solution 4 - Swift

//Swift 4.2

    if objarray.contains(where: { $0.id == 1 }) {
        // print("1 exists in the array")
    } else {
        // print("1 does not exists in the array")
    }

Solution 5 - Swift

A small iteration on @Antonio's solution using the , (where) notation:

if let results = objarray.filter({ $0.id == 1 }), results.count > 0 {
   print("1 exists in the array")
} else {
   print("1 does not exists in the array")
}

Solution 6 - Swift

There are mainly 2 viable options here.

  1. Use the contains(where: method on objarray. I'm just making a minor modification to @TheEye's answer here:
if objarray.contains(where: { $0.id == 1 }) {
    print("1 exists in the array")
} else {
    print("1 does not exists in the array")
}
  1. Override the Equatable protocol conformance requirement and just use contains, like this:
// 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")
}

Solution 7 - Swift

This works fine with me:

if(contains(objarray){ x in x.id == 1})
{
     println("1 exists in the array")
}

Solution 8 - Swift

struct Name {
    var id = Int()
    var name = String()
}

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

var oneExists = !objarray.filter{ $0.id == 1 }.isEmpty

Solution 9 - Swift

signature:

let booleanValue = 'propertie' in yourArray;

example:

let yourArray= ['1', '2', '3'];

let contains = '2' in yourArray; => true
let contains = '4' in yourArray; => false

Solution 10 - Swift

I went with this solution to similar problem. Using contains returns a Boolean value.

var myVar = "James"

if myArray.contains(myVar) {
            print("present")
        }
        else {
            print("no present")
        }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNuibbView Question on Stackoverflow
Solution 1 - SwiftAntonioView Answer on Stackoverflow
Solution 2 - SwiftTheEyeView Answer on Stackoverflow
Solution 3 - Swiftj_gonferView Answer on Stackoverflow
Solution 4 - SwiftDanielvgftvView Answer on Stackoverflow
Solution 5 - SwiftStoff81View Answer on Stackoverflow
Solution 6 - SwiftFrankensteinView Answer on Stackoverflow
Solution 7 - Swiftwhitney13625View Answer on Stackoverflow
Solution 8 - SwiftTheN3wbieView Answer on Stackoverflow
Solution 9 - SwiftricardoaleixooView Answer on Stackoverflow
Solution 10 - SwiftDan KorkeliaView Answer on Stackoverflow