1

I am curious as to the different between these two classes below. As you can see the only difference is that in the second Book class I have title declared as a implicitly unwrapped optional. What is the difference between let title: String & let title: String! They seem to act the same way. Which is better practice?

class Book {

    let title: String

    init(title: String) {
        self.title = title
    }
}

class Book {

    let title: String!

    init(title: String) {
        self.title = title
    }
}
Alex Lacayo
  • 1,462
  • 1
  • 19
  • 27

2 Answers2

2

Don't wrap your values in optionals or implicitly unwrapped optionals unless you have to.

String and String! are two different types. let title: String is just String, whereas let title: String! has the type ImplicitlyUnwrappedOptional<String>. Every access to the string value must be dereferenced through the wrapping type.

To make my point, let's ask a dumb question: why not store the string value in an array?

let title: [String]

let title: [String] has the type Array<String>, and you could access the string value with title.first. The reason you wouldn't do this is because title will only ever have one value, so there is no reason to wrap the value in an enclosing type.

The same is true for the implicitly unwrapped optional. At no point can title ever be nil, so there is no reason to wrap the value in an enclosing type.


That said, without looking at the assembly, I would assume the implicitly unwrapped optional would be optimized out by the compiler.

Jeffery Thomas
  • 42,202
  • 8
  • 92
  • 117
0

The basic difference is that Implicitly Unwrapped optionals are used when you know that after some point of time you know that it will have a value thereafter and will never be nil after that. But still you could use all the functionalities of optionals with Implicitly Unwrapped optionals such as comparing with nil and optional binding.

Now with normal variable you don't have the flexibility of checking it with nil.

Also with implicitly unwrapped optionals you can ensure that you can still pass nil as a value in initializer, but if the value is passed once, it will be never be nil thereafter. Its just that with unwrapped optionals you will get a default value of nil.

But finally it totally depends on your use case.

It is even quoted in swift book available on iTunes:

Implicitly unwrapped optionals are useful when an optional’s value is confirmed to exist immediately after the optional is first defined and can definitely be assumed to exist at every point thereafter. The primary use of implicitly unwrapped optionals in Swift is during class initialization.

Jaycee
  • 159
  • 6