我有Keys數組和對象數組,並且我想創建一個字典,其中鍵數組中的索引Y處的每個鍵都指向對象數組中相同索引Y處的對象,即I想要讓這樣的代碼,但是在斯威夫特2:在swift中創建對象和鍵數組字典
NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithObjects:ObjectsArray forKeys:KeysArray];
我有Keys數組和對象數組,並且我想創建一個字典,其中鍵數組中的索引Y處的每個鍵都指向對象數組中相同索引Y處的對象,即I想要讓這樣的代碼,但是在斯威夫特2:在swift中創建對象和鍵數組字典
NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithObjects:ObjectsArray forKeys:KeysArray];
let keys = [1,2,3,4]
let values = [10, 20, 30, 40]
assert(keys.count == values.count)
var dict:[Int:Int] = [:]
keys.enumerate().forEach { (i) ->() in
dict[i.element] = values[i.index]
}
print(dict) // [2: 20, 3: 30, 1: 10, 4: 40]
或更多的功能和通用的方法
func foo<T:Hashable,U>(keys: Array<T>, values: Array<U>)->[T:U]? {
guard keys.count == values.count else { return nil }
var dict:[T:U] = [:]
keys.enumerate().forEach { (i) ->() in
dict[i.element] = values[i.index]
}
return dict
}
let d = foo(["a","b"],values:[1,2]) // ["b": 2, "a": 1]
let dn = foo(["a","b"],values:[1,2,3]) // nil
這是一個通用的解決方案
func dictionaryFromKeys<K : Hashable, V>(keys:[K], andValues values:[V]) -> Dictionary<K, V>
{
assert((keys.count == values.count), "number of elements odd")
var result = Dictionary<K, V>()
for i in 0..<keys.count {
result[keys[i]] = values[i]
}
return result
}
let keys = ["alpha", "beta", "gamma", "delta"]
let values = [1, 2, 3, 4]
let dict = dictionaryFromKeys(keys, andValues:values)
print(dict)
試試這個:
let dict = NSDictionary(objects: <Object_Array>, forKeys: <Key_Array>)
//Example
let dict = NSDictionary(objects: ["one","two"], forKeys: ["1","2"])
let keyArray = [1,2,3,4]
let objectArray = [10, 20, 30, 40]
let dictionary = NSMutableDictionary(objects: objectArray, forKeys: keyArray)
print(dictionary)
輸出: -
{
4 = 40;
3 = 30;
1 = 10;
2 = 20;
}
爲什麼你剛纔複製什麼上面下面你這傢伙~~已經有了? – hola
@hola我沒有...... – user3441734
在Swift3中,'enumerate'被替換爲'enumerated'。一般來說,Swift 3使用現在時動詞來修改對象和過去式動詞以返回修改後的副本 - 與Python的'sorted'和'sort'進行比較。 – BallpointBen