NSLocale Swift 3

I m*_*ark 13 currency nslocale swift swift3

如何在Swift 3中获取货币符号?

public class Currency: NSObject {
    public let name: String
    public let code: String
    public var symbol: String {
        return NSLocale.currentLocale().displayNameForKey(NSLocaleCurrencySymbol, value: code) ?? ""
    }

    // MARK: NSObject

    public init(name: String, code: String) {
        self.name = name
        self.code = code
        super.init()
    }
}
Run Code Online (Sandbox Code Playgroud)

我知道NSLocale已重命名为Locale,但displayNameForKey已被删除,我似乎只能使用localizedString(forCurrencyCode:self.code)来生成当前语言环境中的货币名称,而无法获取其符号.我正在寻找一种在当前区域设置中获取外币符号的方法.

还是我忽略了什么?

Mar*_*n R 20

NSLocale没有重命名,它仍然存在.Locale是一种在Swift 3中作为值类型包装器引入的新类型(比较SE-0069可变性和基础值类型).

显然Locale没有displayName(forKey:value:)方法,但你总是可以把它转换为它的基础对应物 NSLocale:

public var symbol: String {
    return (Locale.current as NSLocale).displayName(forKey: .currencySymbol, value: code) ?? ""
}
Run Code Online (Sandbox Code Playgroud)

更多例子:

// Dollar symbol in the german locale:
let s1 = (Locale(identifier:"de") as NSLocale).displayName(forKey: .currencySymbol, value: "USD")!
print(s1) // $

// Dollar symbol in the italian locale:
let s2 = (Locale(identifier:"it") as NSLocale).displayName(forKey: .currencySymbol, value: "USD")!
print(s2) // US$
Run Code Online (Sandbox Code Playgroud)


kei*_*ter 5

Locale.current.currencySymbol
Run Code Online (Sandbox Code Playgroud)

Locale类型将大多数字符串类型的属性移动到实际属性中.有关完整的属性列表,请参阅开发人员页面.

  • 这仅适用于当前区域设置的货币符号. (4认同)