cdub cdub - 1 year ago 127
Swift Question

Swift 3 - ! vs ? for optional function parameters

In Swift 3, when one has optional function parameters, what is the difference between functions with:

func doThis(num: Int!)


func doThat(num: Int?)

Answer Source

Both declare that num is an optional Int.

If you do Int! it can be implicitly unwrapped inside of your function. That means you can use it in places where a plain (non-optional) Int is required. In that case, it will fail if it happens to be nil.

With a "proper" Int? the compiler will not let you use num where an Int is required and forces you to include a check/guard first.

The Int! construct is mostly there for interoperability with Objective-C code where it is not clear if a reference type is optional or not. You should avoid it in new code.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download