How do I avoid using the ! operation doing a force unwrap as using this is usually a bad option.
What is the better option with code like the following where using
Your instructor is, broadly speaking, correct. Definitely in this case. There's no reason for making this so special case and forcing duplicated code.
func fullName() -> String {
return [firstName, middleName, lastName] // The components
.flatMap{$0} // Remove any that are nil
.joined(separator: " ") // Join them up
}
This just joins all the non-nil parts of the name with spaces. The other answers here are also fine, but they don't scale as well to adding more optional pieces (like a "Mr." title or "Jr." suffix).
(This is in Swift3 syntax. Swift 2 is very similar, it's joinWithSeparator(_:) instead.)