2016-09-15 32 views
11

如何在Swift 3中获得货币符号?NSLocale 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() 
    } 
} 

我知道NSLocale得到改名为语言环境,但displayNameForKey得到了删除,我只似乎能够使用localizedString(forCurrencyCode:self.code)生成当前区域货币的名称,而不能得到它的象征。我正在寻找一种获取当前语言环境中的外币符号的方法。

还是我忽略了一些东西?

回答

17

NSLocale未被重命名,它仍然存在。 Locale是 在Swift 3中引入的新类型,作为值类型包装器 (比较SE-0069 Mutability and Foundation Value Types)。

显然Locale没有displayName(forKey:value:)方法, 但你总是可以将其转换成其基金会对口 NSLocale

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

更多的例子:

// 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$ 
+0

谢谢你的这些工作,并且看起来比我使用全局Objective-C函数所做的解决方案更加整洁。 –

5
Locale.current.currencySymbol 

Locale型移动大部分字符串类型的属性都变成了真正的属性。请参阅developer pages以获取完整的属性列表。

+3

仅适用于当前语言环境的货币符号。 –

+0

我正在寻找当前语言环境中的外币符号。不适用于外国语言环境中的外币代码。 –

0

我使用扩展区域设置 这是我的代码

extension Int { 
func asLocaleCurrency(identifier: String) -> String { 
    let formatter = NumberFormatter() 
    formatter.numberStyle = .currency 
    formatter.locale = Locale(identifier: identifier) 
    return formatter.string(from: NSNumber(integerLiteral: self))! 
} 
} 

这对于使用

var priceCount = 100000 
priceCount.asLocaleCurrency(identifier: "id_ID") 
0

为SWIFT 3

locale.regionCode 

regionsCode类似于显示名

+0

这将不会打印货币符号... –