假设您的对象定义如下:
struct MyObject {
let firstString: String
let firstDouble: Double
let secondString: String
let secondDouble: Double
}
让我们定义三个对象:
let firstObject = MyObject(firstString: "uno",
firstDouble: 1,
secondString: "un",
secondDouble: 11)
let secondObject = MyObject(firstString: "dos",
firstDouble: 2,
secondString: "deux",
secondDouble: 22)
let thirdObject = MyObject(firstString: "uno",
firstDouble: 3,
secondString: "deux",
secondDouble: 33)
并将它们放在一个数组中:
let myArray: [MyObject] = [firstObject, secondObject, thirdObject]
您可以使用first(where:) 获取其firstString 属性等于"uno" 的第一个元素:
let firstUno: (Int, MyObject)? = myArray
.enumerated()
.first(where: { $0.1.firstString == "uno"})
if let uno = firstUno {
print("First uno index =", uno.0) //First uno index = 0
print("First uno object =", uno.1) //First uno object = MyObject(firstString: "uno", firstDouble: 1.0, secondString: "un", secondDouble: 11.0)
}
您可以执行相同的操作来获取其secondString 属性等于"deux" 的第一个对象:
let firstDeux: (Int, MyObject)? = myArray
.enumerated()
.first(where: { $0.1.secondString == "deux"})
if let deux = firstDeux {
print("First deux index =", deux.0) //First deux index = 1
print("First deux object =", deux.1) //First deux object = MyObject(firstString: "dos", firstDouble: 2.0, secondString: "deux", secondDouble: 22.0)
}