6

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

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
4

3 回答 3

18

使用Sequence'first(where:)方法

您可以使用Sequence'sfirst(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{ $0.uniqId == givenId }?.location ?? ""
print(location) // Hospital

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

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: { $0.uniqId == givenId })?.location {
    print(location) // Hospital
}

可能的替代方法:考虑使用字典

最后,由于元组元素的第一个成员uniqId, 暗示唯一成员,并且它的类型IntHashable,因此您可能需要考虑使用字典而不是元组数组。这将简化与给定唯一IntID 相关联的值的访问,但您将松散字典中“元素”(键值对)的顺序,因为字典是无序的集合。

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
}
于 2016-10-13T20:11:33.037 回答
3

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

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
于 2016-10-13T19:57:10.017 回答
1

你可以试试下面的东西。

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
于 2016-10-13T20:18:25.157 回答