× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Difference between a type and an explicitly unwrapped type in Swift

Antonio Bello
Mar 01, 2015
<p>The implicitly unwrapped optional is an <strong>optional</strong>, in fact you can assign a <code>nil</code> value</p> <pre><code>var s: String! = nil </code></pre> <p>But declaring as implicitly unwrapped, you don't have to append <code>?</code> every time you use it, so, as its name states, it is implicitly unwrapped because it is supposed to contain a non nil value.</p> <p>Consequence: if an implicitly unwrapped is nil, most likely when you use it in your code a runtime exception will be generated - for instance:</p> <pre><code>let s: String! = nil var s1: String = s // Execution was interrupted, reason: EXC_BAD_INSTRUCTION ... </code></pre> <p>The question could turn into: why do implicitly unwrapped optionals exist? The answer is that they are needed to <a href="https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/AutomaticReferenceCounting.html#//apple_ref/doc/uid/TP40014097-CH20-XID_93">Resolving Strong Reference Cycles Between Class Instances</a>, and a few other cases.</p> <p>I would personally avoid declaring implicitly unwrapped variables in my code, unless I have a very good reason (such as to solve reference cycles, as mentioned above)</p> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/26022312/Difference%20between%20a%20type%20and%20an%20explicitly%20unwrapped%20type%20in%20Swift/26022483">Stack Overflow</a>.</p>

Get New Tutorials Delivered to Your Inbox

New tutorials will be sent to your Inbox once a week.

comments powered by Disqus