我正在尝试在代码中构建当前语言环境属性表,但在尝试将变量值传递给函数时遇到了问题:
let currentLocale = Locale(identifier: "en_US")
let calendar1 = currentLocale.calendar // "gregorian (fixed)"
let propertyName = "calendar"
let calendar2 = currentLocale.propertyName // Error: Value of type 'Locale' has no member 'porpertyName'
在上面的最后一行代码中,Locale 的实例认为我传递给它的是“propertyName”而不是变量“calendar”的内容。
有什么方法可以将 propertyName ("calendar") 的值传递给 Locale 的实例吗?我知道在其他语言中,您可以在变量名称前加上“$propertyName”之类的前缀,这会告诉它读取变量的值。
如果可能的话,我想保留这个纯 Swift。
最佳答案
您正在寻找某种形式的 key-value coding .
这有点棘手,因为这是 Cocoa 的纯 Objective-C 特性,所以它不适用于 Swift 覆盖类 Locale;您必须将 currentLocale
转换为 Objective-C NSLocale。此外,NSLocale 通过特殊的 NSLocale.Key 类型公开其属性。经过大量转换后,我发现这行得通:
let calendar2 =
(currentLocale as NSLocale).object(forKey:NSLocale.Key(rawValue:propertyName))
calendar2
的类型为 Any,但您可以将其转换为字符串。
关于swift - 使用变量值进行属性查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39356536/