利用Sequence
的first(where:)
方法
你可以利用Sequence
的first(where:)
方法,根据元组元素的第一个成员(uniqId
)的布尔要求访问数组的第一个元组元素。对于结果元组元素,只需访问元组的第二个成员(location
)。
var pickerDataVisitLocation: [(uniqId: Int, location: String)] =
[(203, "Home"), (204, "Hospital"), (205, "Other")]
let givenId = 204
let location = pickerDataVisitLocation
.first{ $0.uniqId == givenId }?.location ?? ""
print(location)
如果给定id找不到元组元素,则上述方法将导致结果字符串为空(由于nil合并运算符)。作为替代,您可以使用可选绑定子句仅在从.first返回非
nil
时继续进行:
var pickerDataVisitLocation: [(uniqId:Int,location:String)] =
[(203,"Home"),(204,"Hospital"),(205,"Other")]
let givenId = 204
if let location = pickerDataVisitLocation
.first(where: { $0.uniqId == givenId })?.location {
print(location)
}
可能的替代方案:考虑使用字典
最后,由于你的元组元素中的第一个成员uniqId
提示了唯一成员,并且它的类型Int
是可Hashable
的,你可能想考虑使用字典而不是元组数组。这将简化与给定唯一Int
id相关联的值的访问,但您将失去字典中“元素”(键-值对)的顺序,因为字典是无序集合。
var pickerDataVisitLocation = [203: "Home", 204: "Hospital", 205: "Other"]
let givenId = 204
if let location = pickerDataVisitLocation[givenId] {
print(location)
}
selectedIndex
是204,因为它是数组中第1个项目的uniqId
。然后你尝试获取pickerDataVisitLocation[204]
,但它只有3个项目。问题出在哪里?你期望它做什么? - Connor Neville[Int:String]
的字典。 - Knight0fDragonselectedIndex
将会是你所给出的代码中的 203、204 或 205,而你的数组只有 3 个元素。 - Rajan Maheshwari