asma22 asma22 - 1 year ago 55
Swift Question

Swift string vs. string! vs. string?

I have read this question and some other questions. But they are somewhat unrelated to my question


if you don't specify
you will get such an error:

@IBOutlet property has non-optional type 'UILabel'

Which then Xcode gives you 2 choices to have it fixed, you can do:

fix-it Add ? to form the optional type UIlabel?

fix-it Add ! to form
the implicitly unwrapped optional type UIlabel?

However for string you can just type
and you won't get an error why is that?

What happens if the
isn't set? Then we would have a
isn't using
and Swift all about satisfying 'type-safety'?


struct PancakeHouse {
let name: String // this doesn't have '?' nor '!'
let photo: UIImage?
let location: CLLocationCoordinate2D?
let details: String

Answer Source

For your PancakeHouse struct, name is non-optional. That means that its name property cannot be nil. The compiler will enforce a requirement that name be initialized to a non-nil value anytime an instance of PancakeHouse is initialized. It does this by requiring name to be set in any and all initializers defined for PancakeHouse.

For @IBOutlet properties, this is not possible. When an Interface Builder file (XIB or Storyboard) is unarchived/loaded, the outlets defined in the IB file are set, but this always occurs after the objects therein have been initialized (e.g. during view loading). So there is necessarily a time after initialization but before the outlets have been set, and during this time, the outlets will be nil. (There's also the issue that the outlets may not be set in the IB file, and the compiler doesn't/can't check that.) This explains why @IBOutlet properties must be optional.

The choice between an implicitly unwrapped optional (!) and a regular optional (?) for @IBOutlets is up to you. The arguments are essentially that using ! lets you treat the property as if it were non-optional and therefore never nil. If they are nil for some reason, that would generally be considered a programmer error (e.g. outlet is not connected, or you accessed it before view loading finished, etc.), and in those cases, failing by crashing during development will help you catch the bug faster. On the other hand, declaring them as regular optionals, requires any code that uses them to explicitly handle the case where they may not be set for some reason. Apple chose implicitly unwrapped as the default, but there are Swift programmers who for their own reasons, use regular optionals for @IBOutlet properties.