2017-02-28 81 views
2

如何爲字符串擴展添加自定義的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) 
    } 
} 
+2

「*如何將自己設置爲'formattedString' *?」你通常如何執行任務? (*提示提示*) – Hamish

+0

@Hamish足夠有趣,第一次我需要它時,一點都不會發生。從我的Java背景中,我被迫陷入了一個非常特殊的誤導思維。 – Alexander

+0

Hamish,感謝提示:D –

回答

2

值類型的初始化(和變異方法)可以簡單地分配直接到self

import Foundation 

extension String { 
    init(_ amount: Double, decimalPlaces: UInt) { 
     let currencyAmount = String(format: "%\(decimalPlaces).f", amount) 
     let currencySign = NSLocalizedString("Defaults.CurrencySign", comment: "currency sign") 
     self = "\(currencySign)\(currencyAmount)" 
    } 
} 

let price = Double(155.15) 
let formattedPrice = String(price, decimalPlaces: 2) // formattedPrice = "$155.15" 
+0

非常明顯))謝謝,將標記爲正確5分鐘後回答。 –

+1

在字符串內插中使用字符串初始值設定項是多餘的 –

+0

@LeoDabus我剛剛複製了原始代碼,沒有注意到。固定。 – Alexander