<html><head><meta http-equiv="Content-Type" content="text/html charset=utf-8"></head><body style="word-wrap: break-word; -webkit-nbsp-mode: space; -webkit-line-break: after-white-space;" class=""><br class=""><div class="">
<div style="color: rgb(0, 0, 0); letter-spacing: normal; orphans: auto; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; widows: auto; word-spacing: 0px; -webkit-text-stroke-width: 0px; word-wrap: break-word; -webkit-nbsp-mode: space; -webkit-line-break: after-white-space;" class="">Saagar Jha<br class=""><br class="">This isn’t quite how optional chaining in Swift works; see the&nbsp;<a href="https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/OptionalChaining.html" class="">Swift Programming Guide</a>, specifically “Linking Multiple Levels of Chaining". Basically, `s?.characters.count` works because `s.characters` isn’t Optional. You only use ? on properties that are Optional.</div>

</div>
<br class=""><div><blockquote type="cite" class=""><div class="">On Aug 1, 2016, at 10:26, Stephen Schaub via swift-users &lt;<a href="mailto:swift-users@swift.org" class="">swift-users@swift.org</a>&gt; wrote:</div><br class="Apple-interchange-newline"><div class=""><div dir="ltr" class="">With optional chaining, if I have a Swift variable<br class=""><br class="">&nbsp; &nbsp; var s: String?<br class=""><br class="">s might contain nil, or a String wrapped in an Optional. So, I tried this to get its length:<br class=""><br class="">&nbsp; &nbsp; let count = s?.characters?.count ?? 0<br class=""><br class="">However, the compiler wants this:<br class=""><br class="">&nbsp; &nbsp; let count = s?.characters.count ?? 0<div class=""><br class=""></div><div class="">or this:</div><div class=""><br class=""></div><div class="">&nbsp; &nbsp;&nbsp;let count = (s?.characters)?.count ?? 0<br class=""><br class="">My understanding of optional chaining is that, once you start using '?.' in a dotted expression, the rest of the properties evaluate as optional and are typically accessed by '?.', not '.'.<br class=""><br class="">So, I dug a little further and tried this in the playground:<br class=""><br class="">var s: String? = "Foo"<br class="">print(s?.characters)<br class=""><br class="">The result indicates that s?.characters is indeed an Optional instance, indicating that s?.characters.count should be illegal.<br class=""><br class="">Why is s?.characters.count a legal expression?<br class=""><br class=""><br class="">--<br class="">Stephen Schaub
</div></div>
_______________________________________________<br class="">swift-users mailing list<br class=""><a href="mailto:swift-users@swift.org" class="">swift-users@swift.org</a><br class="">https://lists.swift.org/mailman/listinfo/swift-users<br class=""></div></blockquote></div><br class=""></body></html>