如何在Swift中检查属性值是否存在于对象数组中

57
我试图检查一个对象数组中是否存在特定项(属性值),但找不到任何解决方案。请告诉我,我漏掉了什么。
        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")
        }
10个回答

86

你可以这样过滤数组:

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

该函数将返回一个由符合闭包中指定条件的元素组成的数组。在上述情况下,它将返回一个数组,其中包含所有具有id属性等于1的元素。

由于您需要一个布尔结果,只需进行以下检查:

let exists = results.isEmpty == false

exists 将会是 true,如果过滤后的数组至少有一个元素。


26

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

如何在比较成功时返回一个对象? - Hemang
如果你需要更多的条件测试,请使用filter而不是contains。@Hemang - Cœur
如何在where子句下检查一个以上的条件? - IKKA

11

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

11

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

5
这里主要有两个可行的选项。
1. 在`objarray`上使用`contains(where:`方法。我这里只是对@TheEye的答案做了一个小修改:
```swift objarray.contains(where: { $0.someString == "targetValue" }) ```
2. 使用`firstIndex(where:`方法来查找目标值在数组中的索引位置,并进一步进行操作。
if objarray.contains(where: { $0.id == 1 }) {
    print("1 exists in the array")
} else {
    print("1 does not exists in the array")
}
  1. 覆盖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")
}

4

对@Antonio的解决方案进行小改动,使用,where)符号表示:

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

2
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

1
这对我来说很好用:

这个在我这里可以正常工作:

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

0

签名:

let booleanValue = 'propertie' in yourArray;

例子:

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

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

我认为问题陈述了“对象数组”,而不是你提供的“字符串数组”作为示例。因此,这并没有真正回答所问的问题。 - Neil Lunn

-1
我采用了与此类似的解决方案。使用 contains 可返回布尔值。
var myVar = "James"

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接