Reputation: 172
I have this function that accepts an Double value, convert it to a currency format and return a String formatted like R$:1.200,30.
func convert_Value(valor: Double) ->String {
let formatter = NSNumberFormatter()
formatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle
formatter.locale = NSLocale(localeIdentifier: "pt_BR")
return ("\(formatter.stringFromNumber(valor))")
}
This function doesn't have any Optional variable declared, but when i call it using:
x = convert_Value(1200.30)
it returns:
Optional("R$1.200,30")
I can't figure out what i need to do, as its not an optional i can't use exclamation marks to unwrap the optional. I tried to turn the Double and String parameter in function as Optional and then unwrap, but the Optional stills showing.
Upvotes: 2
Views: 1050
Reputation: 22939
It doesn't return Optional("R$1.200,30")
, it returns "Optional("R$1.200,30")"
. There's a subtle difference there; notice the "
. What's happening is formatter.stringFromNumber(valor)
returns String?
, which you're putting in a String
using "\(...)"
. Instead, you should return formatter.stringFromNumber(valor)!
, force unwrapping here is okay because you know the input is a number.
Upvotes: 6