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

前端 未结 9 1506
执笔经年
执笔经年 2020-12-13 09:01

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.<

相关标签:
9条回答
  • 2020-12-13 09:28

    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")
            }
    
    0 讨论(0)
  • 2020-12-13 09:31

    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")
    }
    
    0 讨论(0)
  • 2020-12-13 09:33

    //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")
        }
    
    0 讨论(0)
提交回复
热议问题