title: Why does using dynamicType on a force unwrapped nil optional value type work?
body: <p>I was really confused to find that the following code simply refuses to crash with the typical “<em>Unexpectedly found nil while unwrapping an Optional value</em>” exception that you’d expect from force unwrapping <code>bar</code>.</p>
  
  <pre><code>struct Foo {
      var bar: Bar?
  }
  struct Bar {}
  
  var foo = Foo()
  
  debugPrint(foo.bar) // nil
  debugPrint(foo.bar!.dynamicType) // _dynamicType.Bar
  </code></pre>
  
  <p>It seems <code>dynamicType</code> is <em>somehow</em> able to fallback to the defined type of <code>bar</code> – without crashing.</p>
  
  <p>Note this only appears to happen when <code>Bar</code> is defined as a <em>value</em> type (as <a href="https://stackoverflow.com/questions/36824048/why-does-using-dynamictype-on-a-force-unwrapped-optional-struct-not-crash#comment61221761_36824048">@dfri says</a>), <code>Foo</code> is a <code>struct</code> or <code>final class</code> (as <a href="https://stackoverflow.com/questions/36824048/why-does-using-dynamictype-on-a-force-unwrapped-optional-struct-not-crash#comment61219783_36824048">pointed out by @MartinR</a>) &amp; <code>foo</code> is mutable.</p>
  
  <p>I did initially consider that it could just be a compiler optimisation due to the fact that the type of <code>bar</code> is known at compile time, so therefore the force unwrapping could have been optimised away – but it also crashes when <code>Bar</code> is defined as a <code>final class</code>. Furthermore, if I set the "Optimisation Level" to <code>-Onone</code>, it still works.</p>
  
  <p>I’m inclined to think this is a weird bug, but would like some confirmation.</p>
  
  <p>Is this a bug or a feature with <code>dynamicType</code>, or am I simply missing something here?</p>
  
  <p><sub>(Using Xcode 7.3 w/ Swift 2.2)</sub></p>
  
  <hr>
  
  <h3>Swift 4.0.3 update</h3>
  
  <p>This is still reproducible (with an even more minimal example) in Swift 4.0.3:</p>
  
  <pre><code>var foo: String?
  print(type(of: foo!)) // String
  </code></pre>
  
  <p>Here we're using <code>dynamicType</code>'s successor, <code>type(of:)</code>, to get the dynamic type; and like the previous example, it doesn't crash.</p>