<div dir="ltr">You can think of this like flatMap:<div><br></div><div> let count = s.flatMap { $0.characters.count } ?? 0 // like s?.characters.count ?? 0</div><div> let count = s.flatMap { $0.characters }.flatMap { $0.count } ?? 0 // like (s?.characters)?.count ?? 0</div><div class="gmail_extra"><br clear="all"><div><div class="gmail_signature" data-smartmail="gmail_signature"><div dir="ltr"><div>Jacob<br></div></div></div></div>
<br><div class="gmail_quote">On Mon, Aug 1, 2016 at 10:26 AM, Stephen Schaub via swift-users <span dir="ltr"><<a href="mailto:swift-users@swift.org" target="_blank">swift-users@swift.org</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex"><div dir="ltr">With optional chaining, if I have a Swift variable<br><br> var s: String?<br><br>s might contain nil, or a String wrapped in an Optional. So, I tried this to get its length:<br><br> let count = s?.characters?.count ?? 0<br><br>However, the compiler wants this:<br><br> let count = s?.characters.count ?? 0<div><br></div><div>or this:</div><div><br></div><div> let count = (s?.characters)?.count ?? 0<br><br>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><br>So, I dug a little further and tried this in the playground:<br><br>var s: String? = "Foo"<br>print(s?.characters)<br><br>The result indicates that s?.characters is indeed an Optional instance, indicating that s?.characters.count should be illegal.<br><br>Why is s?.characters.count a legal expression?<br><br><br>--<br>Stephen Schaub
</div></div>
<br>_______________________________________________<br>
swift-users mailing list<br>
<a href="mailto:swift-users@swift.org">swift-users@swift.org</a><br>
<a href="https://lists.swift.org/mailman/listinfo/swift-users" rel="noreferrer" target="_blank">https://lists.swift.org/mailman/listinfo/swift-users</a><br>
<br></blockquote></div><br></div></div>