如何为String扩展添加自定义init?

时间:2017-02-28 21:28:39

标签: swift initialization

如何为String扩展添加自定义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)
    }
}

1 个答案:

答案 0 :(得分:5)

值类型的初始化器(和变异方法)可以直接分配给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"