[swift-users] Optional chaining and String properties
Jacob Bandes-Storch
jtbandes at gmail.com
Mon Aug 1 22:28:31 CDT 2016
You can think of this like flatMap:
let count = s.flatMap { $0.characters.count } ?? 0 // like
s?.characters.count ?? 0
let count = s.flatMap { $0.characters }.flatMap { $0.count } ?? 0 //
like (s?.characters)?.count ?? 0
Jacob
On Mon, Aug 1, 2016 at 10:26 AM, Stephen Schaub via swift-users <
swift-users at swift.org> wrote:
> With optional chaining, if I have a Swift variable
>
> var s: String?
>
> s might contain nil, or a String wrapped in an Optional. So, I tried this
> to get its length:
>
> let count = s?.characters?.count ?? 0
>
> However, the compiler wants this:
>
> let count = s?.characters.count ?? 0
>
> or this:
>
> let count = (s?.characters)?.count ?? 0
>
> 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 '.'.
>
> So, I dug a little further and tried this in the playground:
>
> var s: String? = "Foo"
> print(s?.characters)
>
> The result indicates that s?.characters is indeed an Optional instance,
> indicating that s?.characters.count should be illegal.
>
> Why is s?.characters.count a legal expression?
>
>
> --
> Stephen Schaub
>
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160801/25472a90/attachment.html>
More information about the swift-users
mailing list