我在Objective c中有一个函数来获取字典的值,该字典传递带有不敏感键的键。
我在Objective c中的功能是:
-(UIFont *) languageFont {
NSDictionary * users = @{@"Aaron" : @"English", @"Alice" : @"English", @"John" : @"Brasilian"};
NSString * countryLaunguage = [users objectForInsensitiveKey:@"Alice"];
return countryLaunguage;
}
如何将该函数转换为Swift?因为在字典中我找不到从键返回值的类似函数?
谢谢!
答案 0 :(得分:0)
具有Dictionary的扩展名并使用该功能。
extension Dictionary where Key == String {
subscript(insensitive key: Key) -> Value? {
get {
if let k = keys.first(where: { $0.caseInsensitiveCompare(key) == .orderedSame }) {
return self[k]
}
return nil
}
set {
if let k = keys.first(where: { $0.caseInsensitiveCompare(key) == .orderedSame }) {
self[k] = newValue
} else {
self[key] = newValue
}
}
}
}
示例:
var dict = ["Aaron" : "English", "Alice" : "English", "John" : "Brasilian"]
print(dict[insensitive: "alice"]!) // outputs "English"
希望这能回答您的查询。