Group Group Group Group Group Group Group Group Group

Currency Formatter Question

Hello!

I’ve created the following struct to manage some json data that I’m importing into my app. I’m using the following code to convert a double into US currency, but I don’t understand why xcode/swift is asking me to both nil coalesce and else return “n/a”… why the redunant "N/A"s??

everything is working as I hoped, I just don’t understand the code all that well. I would except the Else statement would suffice, but xcode auto fixes with the ?? “N/A” too.

Any ideas?

struct Record: Codable, Identifiable {

let id: Int

let gf: Double?


var formattedGF: String {
    if let gf = gf {
        let currencyFormatter = NumberFormatter()
        currencyFormatter.numberStyle = .currency
        
        let usLocale = Locale(identifier: "en_US")
        currencyFormatter.locale = usLocale
        return currencyFormatter.string(from: NSNumber(value: gf)) ?? "N/A"
    } else {
        return "N/A"
    }
}

}

Hi @dmalicke, because the constant gf is an optional there has to be a default value in case there is no value available. As for else statement, it seems like it’s only there as a backup in case gf does not have a value and if that was the case then we’d be returning a string “N/A”. You could remove the else statement and return a string but either way, we have to have some sort of return that is of type string.

Best,
Gina

Thanks so much! I really really appreciate this response, and it clears it up for me perfectly.

Have a great day!

1 Like

This is not the true reason for XCode requiring ?? “N/A”.

the first if statement is an optional binding, turning the optional variable gf into a non optional variable gf in the first part of the test

However the method string(from:) of the NumberFormatter class returns an optional String and since the read-only computed property formattedGF is a non optional String, the returns must be non optional.

As a side note, not related, the else statement is not required here. Since the first part of the test always returns something, there is no need for a else

var formattedGF: String 
{
 if let gf = gf
 {
  ...
  return currencyFormatter.string(from: NSNumber(value: gf)) ?? "N/A"
 }

 return "N/A"
}

I would have use a guard instead, but only because I like it more this way. I find it more readable to start with not valid tests

var formattedGF: String
{
 guard let gf = gf else { return "N/A" }

 ...
 return currencyFormatter.string(from: NSNumber(value: gf)) ?? "N/A"
}

@mokhet thank you for bringing this to my attention and for sharing your answer. You make a great point and your response is appreciated. Have a great weekend!

Best,
Gina