The Miotz The Miotz - 1 month ago 24
iOS Question

iOS Swift: Formatting a custom Currency Number

Formatting large numbers with comma separator.



Solved (The code is updated and fully working)



Evening, I have a typealias
Currency
from
Double
.

I want to print it with the comma between the thousands.

this is what I did:

import Foundation

typealias Currency = Double

extension Currency {
var credit: Double { return self }
var usd: Double { return self * 0.62 }

func description() -> String {
let price = self as NSNumber
let formatter = NumberFormatter()
formatter.numberStyle = .currency
return formatter.string(from: price)!
}

}

let price: Currency = 1000000000

print(price.description)
/* It doesn't work, I want something like 1000,000,000.0 */


But it doesn't work. What is wrong?

Answer

description is a property that comes baked into Foundation via the CustomStringConvertible protocol which states the description variable as:

A textual representation of the value.

You're looking to call your description() method. Add parentheses and you'll get your desired result:

price.description()