Sequence
のfirst(where:)
方法を利用する
を使用して、タプル要素 ( ) の最初のメンバーに基づくブール要件を満たす配列の最初のタプル要素にアクセスできSequence
ます。結果のタプル要素については、タプルの 2 番目のメンバー ( ) にアクセスするだけです。first(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 のため)。別の方法として、オプションのバインディング句を使用して、非nil
return 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
一意のメンバーを示しており、その型Int
はHashable
であるため、タプルの配列ではなく辞書の使用を検討することをお勧めします。これにより、与えられた一意の 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
}