Hey I have been looking at some really good question on here. About how to convert a Array to a dictionary but the problem is that is doesn't keep the same order Example:
list = ["test", "test2", "test3"]
outPut:
listNewFromExt = ["test": "test","test3": "test3", "test2": "test2"]
Basically test3 is being switched places with test2
Code:
let listNewFromExt = list.toDictionary{($0, $0)}
extension Sequence {
public func toDictionary<K: Hashable, V>(_ selector: (Iterator.Element) throws -> (K, V)?) rethrows -> [K: V] {
var dict = [K: V]()
for element in self {
if let (key, value) = try selector(element) {
dict[key] = value
}
}
return dict
}
}
Also if you could tell me how to just make the .values "nil" instead of a copy of the key that would be great lol.
See Question&Answers more detail:os