Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
537 views
in Technique[技术] by (71.8m points)

How to convert Array to Dictionary while keeping the same order Swift

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In Swift, a Dictionary is an unordered collection by design. Therefore you can't keep any order to it after migrating from an Array.

If you want your values to be nil, just use

let dict = Dictionary<Int, Any?>(uniqueKeysWithValues: [1, 2, 3].map { ($0, nil) })

This evaluates to [2: nil, 3: nil, 1: nil]

If you want some sort of sorting (no pun intended), you may convert the dict to a sorted tuple array:

let sortedTupleArray = dict.sorted { $0.key > $1.key }

This evaluates to [(key: 3, value: nil), (key: 2, value: nil), (key: 1, value: nil)]


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...