init?

I’d been wondering why, when creating some types in Swift I was seeing a requirement to unwrap the type. After all, surely if I created a types it’s not nil and hence why does it need to be optional?

Well Swift does actually allow us to declare a type’s init as optional, for example

struct Email {
   var address: String

   init?(address: String) {
      // not really much of a validation step
      // but in the real world we could ensure
      // the address matches an email regex
      guard address.count > 0 else {
         return nil
     }
   }
}

This is pretty useful as it means if we initialize a type with invalid values, we can simple return a nil optional object instead of the alternative of throwing an exception or the need for a two phase initialization.