I have an array of arrays like
var arr = [[("aa",1),("b",2)],[("c",3),("dd",4)],[("e",5),("f",6)]]
I want to find first index of dd in arr. I am trying this code but failed to get result
let val = arr.first(where: {$0.1 == "dd" })
You used multi-dimensional arrays, please clarify which index do you looking for(inner/outer index).
In case you mean outer array index:
let outerIndex = arr.firstIndex(where: { $0.contains(where: { $0.0 == "dd"}) })
In case you mean inner array index:
let innerIndex = arr.map({ $0.firstIndex(where: { $0.0 == "dd" }) }).filter({ $0 != nil }).first
In case you need both indexes:
var bothIndex: (outer: Int?, inner: Int?) {
guard let outerIndex: Int = arr.firstIndex(where: { $0.contains(where: { $0.0 == "dd"}) }) else {
assertionFailure()
return (nil,nil)
}
let innerIndex: Int? = arr[outerIndex].firstIndex(where: { $0.0 == "dd"})
return (outerIndex, innerIndex)
}
First of all tuples are indexed from 0 so it should be $0.0 and to find an index you need to use firstIndex and lastly, since you have an array of arrays you need to drill down one level and then return when you have a match in an inner array, I use contains for the inner arrays
let val = arr.firstIndex(where: {
$0.contains(where: { tuple in tuple.0 == "dd" })
})
From the your code, you have an value to each letter like "aa" has 1, "b" has 2, and so on.
If you want to find the value corresponding to "dd", I would suggest you to use Hashmaps/Dictionary !!
So your code will be
var values = ["aa":1, "b":2, "c":3, "dd":4, "e":5, "f":6]
let val = values["dd"] //val = 4
You have an array of arrays. You would need the index of the outer as well as the inner array:
var arr = [[("aa",1),("b",2)],[("c",3),("dd",4)],[("e",5),("f",6)]]
let predicate: ((String,Int)) -> Bool = { $0.0 == "dd" }
if let index = arr.firstIndex(where: {$0.contains(where: predicate)}),
let subIndex = arr[index].firstIndex(where: predicate) {
print(arr[index][subIndex]) // ("dd", 4)
}
Expanding on that subject:
extension Collection where Element: Collection {
func firstIndexAndSubIndex(where predicate: (Element.Element) -> Bool) -> (index: Index, subIndex: Element.Index)? {
if let index = firstIndex(where: {$0.contains(where: predicate)}),
let subIndex = self[index].firstIndex(where: predicate) {
return (index,subIndex)
}
return nil
}
}
usage:
var arr = [[("aa",1),("b",2)],[("c",3),("dd",4)],[("e",5),("f",6)]]
if let idxs = arr.firstIndexAndSubIndex(where: { $0.0 == "dd" } ) {
print(arr[idxs.index][idxs.subIndex]) // ("dd", 4)
}