NSArray *keys = @[@"one", @"two", @"three"];
NSArray *values = @[@1, @2, @3];
NSDictionary *dict = [[NSDictionary alloc] initWithObjects: values forKeys: keys];
if user.isEligible() {
[dict setObject:@"Hi" forKey:@"Eligible"];
}
我已经看到了here给出的答案,但这不是我要找的
我需要在Swift中存储Dictionary
而不是NSDictionary
,我需要initWithObjects:forKeys
函数的确切翻译
我希望这个dict
是可变的,以便我可以添加对象,就像我在if-condition
内添加一样。
答案 0 :(得分:2)
您可以在extension
广告中使用此功能创建便利初始值设定项:
for (key, value) in zip(keys, values) {
self[key] = value
}
zip函数基本上返回:
一对元组对,其中每对元素都是 sequence1和sequence2的相应元素。
答案 1 :(得分:1)
Swift中没有文字等效词。
您可以创建NSDictionary
并将其投射到Swift Dictionary
。 var
关键字使其变得可变。
let keys = ["one", "two", "three"]
let values = [1, 2, 3]
var dict = NSDictionary(objects: values, forKeys: keys as [NSCopying]) as! [String:Any]
if user.isEligible() {
dict["Eligible"] = "Hi"
}
但是因为键和对象都是用文字创建的,所以我推荐使用原生语法
var dict : [String:Any] = ["one" : 1, "two" : 2, "three : 3]
只有在添加[String:Any]
等其他类型时才需要显式注释Int
。
答案 2 :(得分:1)
另一种方法是在Swift的Dictionary
类型中添加一个扩展名,以添加一个方便的初始化程序,它接受一组键和一组值。
extension Dictionary {
init(keys: [Key], values: [Value]) {
self.init()
for (key, value) in zip(keys, values) {
self[key] = value
}
}
}
测试出来:
let keys1 = [1, 2, 3, 4, 5]
let values1 = ["a", "b", "c", "d", "e"]
var resultDict1 : [Int: String] = Dictionary(keys: keys1, values: values1)
// Result [5 : "e", 2: "b", 1: "a", 3: "c", 4: "d"]
通过在内部使用zip
,初始化程序可以处理keys
和values
数组的长度可能不匹配的事实:
let keys2 = [1, 2, 3, 4, 5, 6]
let values2 = ["a", "b", "c", "d", "e"]
var resultDict2 : [Int: String] = Dictionary(keys: keys, values: values)
// Result [5 : "e", 2: "b", 1: "a", 3: "c", 4: "d"]
答案 3 :(得分:0)
Swift文字字典语法如下:
line-height: 50px;
答案 4 :(得分:0)
你也喜欢这样,因为swift typeSafe语言..
let param = ["key1" : "value1",
"key2" : "value2",
"key2" : "value3"]
如果你想要它,你可以像这样做你的功能..
let keys = [1,2,3,4]
let values = [10, 20, 30, 40]
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]
for Generic
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(["x","y"],values:[1,2]) // ["x": 2, "y": 1]
let dn = foo(["a","b"],values:[1,2,3]) // nil