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.
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
@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!