Vasilii Muravev Vasilii Muravev -4 years ago 192
Swift Question

How to add custom init for String extension?

How can I add custom init method for String extension?

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` ?
}
}


As result I want to see something like this:

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


UPDATED: Final solution

extension String {
init?(_ amount: Double, decimalPlaces: UInt, currencySignLast: Bool?) {
let currencyAmount = String(format: "%0.\(decimalPlaces)f", amount)
let currencySign = NSLocalizedString("Defaults.CurrencySign", comment: "currency sign")
var formattedString = "\(currencySign)\(currencyAmount)"
if currencySignLast == true {
formattedString = "\(currencyAmount)\(currencySign)"
}
self = formattedString
}
}

Answer Source

The initializers (and mutating methods) of value types can simply assign directly to 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"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download