2016-09-15 33 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

這將不會打印貨幣符號... –