如何爲字符串擴展添加自定義的init方法?如何爲字符串擴展添加自定義初始化?
extension String {
init(_ amount: Double, decimalPlaces: UInt) {
self.init()
let decimalFormat = "%0.\(String(decimalPlaces))f"
let currencyAmount = String(format: decimalFormat, amount)
let currencySign = NSLocalizedString("Defaults.CurrencySign", comment: "currency sign")
let formattedString = "\(currencySign)\(currencyAmount)"
// How to set self to `formattedString` ?
}
}
至於結果,我希望看到這樣的事情:
let price = Double(155.15)
let formattedPrice = String(price, decimalPlaces: 2) // formattedPrice = "$155.15"
更新:最終的解決方案
extension String {
init?(currencyAmount: Double) {
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.locale = Locale(identifier: NSLocalizedString("Defaults.LocaleCurrencyFormat", comment: "currency sign")) // Defaults.LocaleCurrencyFormat equal "es_US" for US
let formattedAmount = formatter.string(from: NSNumber(value: currencyAmount)) ?? ""
self.init(formattedAmount)
}
}
「*如何將自己設置爲'formattedString' *?」你通常如何執行任務? (*提示提示*) – Hamish
@Hamish足夠有趣,第一次我需要它時,一點都不會發生。從我的Java背景中,我被迫陷入了一個非常特殊的誤導思維。 – Alexander
Hamish,感謝提示:D –