如何获取swift中的键值对元组数组?

How to Get key value pair tuple array in swift?

我有成对的元组数组pickerDataVisitLocation.just我想知道如何使用 uniqId ex 204 return 从我的数组中定位键值对

var pickerDataVisitLocation:[(uniqId:Int,location:String)] = [(203,"Home"),(204,"Hospital"),(205,"Other")]
var selectedIndex = pickerDataVisitLocation[1].uniqId
pickerDataVisitLocation[selectedIndex].location //<--fatal error: Index out of range

根据给定的代码:
试试这个

var pickerDataVisitLocation:[(uniqId:Int,location:String)] = [(203,"Home"),(204,"Hospital"),(205,"Other")]
let selectedIndex = pickerDataVisitLocation[1].uniqId
var location = ""

for item in pickerDataVisitLocation {
    if item.uniqId == selectedIndex {
        location = item.location
    }
}

print(location) //Will print Hospital here

利用Sequencefirst(where:)方法

您可以利用 Sequencefirst(where:) 来访问满足基于元组元素第一个成员的布尔要求的数组的第一个元组元素 (uniqId).对于生成的元组元素,只需访问元组的第二个成员 (location).

var pickerDataVisitLocation: [(uniqId: Int, location: String)] = 
    [(203, "Home"), (204, "Hospital"), (205, "Other")]

// say for a given uniqId 204
let givenId = 204
let location = pickerDataVisitLocation
               .first{ [=10=].uniqId == givenId }?.location ?? ""
print(location) // Hospital

如果对于给定的 id 找不到元组元素,上述方法将导致生成的字符串为空(由于 nil 合并运算符)。作为替代方案,您可以使用可选的绑定子句仅针对来自 .first:

的非 nil return
var pickerDataVisitLocation: [(uniqId:Int,location:String)] = 
    [(203,"Home"),(204,"Hospital"),(205,"Other")]

// say for a given uniqId 204
let givenId = 204
if let location = pickerDataVisitLocation
                  .first(where: { [=11=].uniqId == givenId })?.location {
    print(location) // Hospital
}

可能是替代方案:考虑使用字典

最后,由于元组元素的第一个成员 uniqId 暗示唯一成员,并且其类型 IntHashable,您可能需要考虑使用字典而不是元组数组。这将简化与给定唯一 Int id 关联的值的访问,但您将失去字典中 "elements"(键值对)的排序,因为字典是无序集合。

var pickerDataVisitLocation = [203: "Home", 204: "Hospital", 205: "Other"]

// say for a given uniqId 204
let givenId = 204
if let location = pickerDataVisitLocation[givenId] {
    print(location) // Hospital
}

您可以试试下面的方法。

extension Array {
    func tupleWithId(id: Int) -> (uniqId:Int,location:String)? {
        let filteredElements = self.filter { (tuple) -> Bool in
            if let tuple = tuple as? (uniqId:Int,location:String) {
                return tuple.uniqId == id
            }
            return false
        }

        if filteredElements.count > 0 {
            let element = filteredElements[0] as! (uniqId:Int,location:String)
            return element
        }
        return nil
    }
}
var pickerDataVisitLocation:[(uniqId:Int,location:String)] = [(203,"Home"),(204,"Hospital"),(205,"Other")]
var selectedIndex = pickerDataVisitLocation[1].uniqId
pickerDataVisitLocation.tupleWithId(id: selectedIndex)?.location