I have pairs tuple array pickerDataVisitLocation.just I want to know how to return key value pair location from my array using 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
Sequence
's first(where:)
methodYou could make use of Sequence
's first(where:)
to access the first tuple element of the array that meets a boolean requirement based on the first member of the tuple elements (uniqId
). For the resulting tuple element, simply access the second member of the tuple (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
If no tuple element can be found for a given id, the method above will result in a resulting string that is empty (due to the nil coalescing operator). As an alternative, you could use an optional binding clause to proceed only for a non-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
}
Finally, since the first member of you tuple elements, uniqId
, hints at unique members, and its type Int
being Hashable
, you might want to consider making use of a dictionary rather than an array of tuples. This will ease access of values associated with give unique Int
id's, but you will loose the ordering of "elements" (key-value pairs) in the dictionary, as dictionaries are unordered collections.
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
}
According to the given code:
Try this
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With