M
M
MoXyLe2017-03-05 19:19:07
Mobile development
MoXyLe, 2017-03-05 19:19:07

What's the difference in optionals in Swift?

Can't understand the difference between optionals and implicitly extracted optionals

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Zhilin, 2017-03-05
@MoXyLe

Implicitly Unwrapped Optionals generally behave like Optionals. In fact, they are converted to Optional at every opportunity:

let x: Int! = 42
let y = x   // y has type Int?

There are two differences: first, you can cast IUO to a non-optional type:
func f(_ arg: Int) { print(arg) }

let x: Int! = 42

let y: Int = x
let z = x as Int
f(x)

Secondly, you can call the methods of the object itself on such a variable. If the IUO contains nil, then the application will crash with the appropriate message:
struct Dog {
    func bark() { print("Woof!") }
}

let d: Dog! = Dog()
d.bark()

IUOs are used, mainly for lazy initialization:
class Foo {
    var x: Int!

    init() {
        // I can't setup x at this point :(
        x = nil
    }

    func setup(x newValue: Int) { x = newValue }

    func foo() {
        // I promise that setupX() will be called before
        // I will deal with x as if it was always present
        print(x * 2)
    }
}

I note that, starting with Swift 3, IUO is not a type at all, but only an attribute of a variable that allows implicit conversions with it. "Under the hood" everything looks something like this:
let x: Int! = 42
@implicitlyUnwrapped let x: Optional<Int> = .some(42)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question