【问题标题】:How to get a value from a dictionary using objectForInsensitiveKey in Swift?如何在 Swift 中使用 objectForInsensitiveKey 从字典中获取值?
【发布时间】:2018-08-25 18:49:01
【问题描述】:

我在 Objective c 中有一个函数来获取字典的值,并通过不敏感的键传递一个键。

我在 Objective c 中的功能是:

-(UIFont *) languageFont {
    NSDictionary * users = @{@"Aaron" : @"English", @"Alice" : @"English", @"John" : @"Brasilian"};

    NSString * countryLaunguage = [users objectForInsensitiveKey:@"Alice"];

    return countryLaunguage;
}

我怎样才能把这个函数翻译成 Swift?因为在字典中我找不到从键返回值的类似函数?

谢谢!

【问题讨论】:

  • 什么是objectForInsensitiveKey?

标签: ios objective-c arrays swift dictionary


【解决方案1】:

拥有字典的扩展并使用该功能。

  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"

希望这能回答您的问题。

【讨论】:

    猜你喜欢
    • 2017-10-31
    • 2022-12-17
    • 2014-11-02
    • 2018-12-10
    • 1970-01-01
    • 2015-02-16
    • 2019-04-23
    • 1970-01-01
    • 2016-07-22
    相关资源
    最近更新 更多