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

Sequencefirst(where:)方法を利用する

を使用して、タプル要素 ( ) の最初のメンバーに基づくブール要件を満たす配列の最初のタプル要素にアクセスできSequenceます。結果のタプル要素については、タプルの 2 番目のメンバー ( ) にアクセスするだけです。first(where:)uniqIdlocation

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であるため、タプルの配列ではなく辞書の使用を検討することをお勧めします。これにより、与えられた一意の ID に関連付けられた値へのアクセスが容易になりますがInt、辞書は順序付けされていないコレクションであるため、辞書内の「要素」(キーと値のペア) の順序が失われます。

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 に答える