Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Optional binding with dictionary

Hello,

I tried optional binding on a dictionary, it works but i have the xcode warning : "Expression implicitly coerced from "Any?" to Any " one the print(name) line. I thought the if let unwrap optional ? Here is the code :

if let name = dictionary["group"]?["person"] {
    print(name)
}

thanks !

Can you please show me the dictionary that you created so that we can help you? We don't know if group of person is a value. But I think I have a solution already. Just show the CODE!

It's json data, looks like :

{ "group": {
        "creation": "05/29/2017"
        "person": ["John Doe", "Claire Stinson"]
         }
}

Oh, I haven't gone over JSON data arrays. Thanks for showing the code anyway.

1 Answer

Nathan F.
Nathan F.
30,773 Points

I believe you can safely disregard this warning, as this is something specific to the print() function.. print needs to output a string to the console, so it coerces the type into something it can display. If you change your code to print(name.localizedDescription) I believe this will disappear.

However, what you would likely want to do in this case is try to cast your name value to String, so what you would do is this:

if let name = dictionary["group"]?["person"] as? String {
    print(name)
}

Thanks Nathan for this explanation !

Nathan F.
Nathan F.
30,773 Points

You're very welcome!