For handling two optional values, which way is better?
switch (self.region, timeZone.abbreviation(for: selection.wrappedValue)) {
case let (.some(region), .some(abbreviation)):
return "\(region) (\(abbreviation))"
case let (.some(region), _):
return region
case let (_, .some(abbreviation)):
return "(\(abbreviation))"
default:
return " "
}
if let region = self.region, let abbreviation = timeZone.abbreviation(for: selection.wrappedValue) {
return "\(region) (\(abbreviation))"
} else if let region = self.region {
return region
} else if let abbreviation = timeZone.abbreviation(for: selection.wrappedValue) {
return "(\(abbreviation))"
} else {
return " "
}
Style? You have to decide yourself, because there is no official style guide.
How easy it is to make mistakes? Switch is great at making sure you write all the cases, but you're using default which bypasses that safety feature. Tie.
How fast it is? Compiler explorer shows they generate similar amount of assembly (Compiler Explorer), but in 2 abbreviation(for:) is called twice. 1 wins here (but if you care about performance, you should benchmark it!)
I have to specifically return a one space string when both are nil...because the result of this is shown on screen with SwiftUI.Text. If I return an empty string "", the Text("") is nothing which mess up my layout. So I give it one space string for the Text to take up the room.
let base = [
region,
abbreviation.map({ "(\($0))" }),
].compactMap({ $0 })
.joined(separator: " ")
// Avoid returning the empty String to make sure a Text always takes some space
return base.isEmpty ? " " : base
switch (self.region, timeZone.abbreviation(for: selection.wrappedValue)) {
case let (.some(region), .some(abbreviation)):
return "\(region) (\(abbreviation))"
case let (.some(region), nil):
return region
case let (nil, .some(abbreviation)):
return "(\(abbreviation))"
default:
return " "
}
You can write case (nil, nil): instead of default so that you explicitly check all possible cases (and switch compilation protects you in ensuring that you did get all cases)