Reputation: 9586
How would I write the following code correctly in Swift 4.2:
let navStack = ["root", "page1", "page3"]
let route = ["root", "page1", "page2", "page3"]
let routeTags =
[
"root": ["root"],
"page1": ["page1", "page2"],
"page3": ["page3"]
]
let r = navStack.map({ routeTags[$0] }).joined(separator: "/")
The current code doesn't compile (ambiguous reference to member 'subscript'). The code should produce a string with the dictionary values mapped according to the keys in navStack
.
Upvotes: 0
Views: 66
Reputation: 285290
Two issues:
routeTags[$0]
is an optional and must be unwrapped (safely with compactMap
).joined
expression must be moved into the closure because the second item is an array.let navStack = ["root", "page1", "page3"]
let route = ["root", "page1", "page2", "page3"]
let routeTags =
[
"root": ["root"],
"page1": ["page1", "page2"],
"page3": ["page3"]
]
let r = navStack.compactMap{ routeTags[$0]?.joined(separator: "/") }
Or you have to use joined
twice if you want one single string:
let r = navStack.compactMap{ routeTags[$0]?.joined(separator: "/") }.joined(separator: "/")
Upvotes: 1