concept optional string in category swift

appears as: optional strings, n optional string
Swift in Depth

This is an excerpt from Manning's book Swift in Depth.

The chapter starts with what optionals are and how Swift helps you by adding syntactic sugar. Then we go over style tips paired with bite-sized examples that you regularly encounter in Swift. After that, you’ll see how to stop optionals from propagating inside a method via a guard. We also cover how to decide on returning empty strings versus optional strings. Next, we show how to get more granular control over multiple optionals by pattern matching on them. Then, you’ll see that you can fall back on default values with the help of the nil-coalescing operator.

4.5. Returning optional strings

In real-world applications, you may be tempted to return an empty string because it saves the hassle of unwrapping an optional string. Empty strings often make sense, too, but in this scenario, they aren’t beneficial. Let’s explore why.

In such a scenario, a better method is to be explicit and tell the implementers of the method that the string can be optional; you do this by making displayName return an optional string.

The benefit of returning an optional String is that you would know at compile-time that displayName may not have a value, whereas with the isEmpty check you’d know it at runtime. This compile-time safety comes in handy when you send out a newsletter to 500,000 people, and you don’t want it to start with “Dear ,”.

Returning an optional string may sound like a strawman argument, but it happens plenty of times inside projects, especially when developers aren’t too keen on optionals. By not returning an optional, you are trading compile-time safety for a potential runtime error.

To set the right example, displayName would return an optional String for display-Name.

Listing 4.17. Making displayName return an optional String
struct Customer {
   // ... snip

    var displayName: String? {                                           #1
       guard let firstName = firstName, let lastName = lastName else {
         return nil                                                      #2
       }
       return "\(firstName) \(lastName)"
    }
}

Now that displayName returns an optional String, the caller of the method must deal with unwrapping the optional explicitly. Having to unwrap displayName, as shown next, may be a hassle, but you get more safety in return.