Reputation: 273
How to get last element on Swift ?
var test: [Int:String] = [Int:String]()
test[1] = "CCC"
test[3] = "AAA"
test[2] = "BBB"
I am trying to get Int 3. I try to use endIndex like this
let (key,value) = test.endIndex
and
print(test.endIndex)
but it does not work.
Upvotes: 3
Views: 6118
Reputation: 18181
You haven't been very clear, but I think you're trying to get the last element of an ordered dictionary. Swift's native Dictionary type is unordered, so you will have to manually sort it:
test.keys.sort().last.map({ ($0, test[$0]!) })
In your specific case, the code above will return Optional((3, "AAA"))
(i.e. typed Optional<(Key, Value )>
).
Upvotes: 5