Flight-School / AnyCodable

Type-erased wrappers for Encodable, Decodable, and Codable values
https://flight.school/books/codable
MIT License
1.28k stars 132 forks source link

Strings only work when it's a literal? #49

Closed alexisbronchart closed 3 years ago

alexisbronchart commented 3 years ago

I'm trying this and getting this error:

Screenshot 2021-01-29 at 09 48 41

Is this a bug or does it work only with literals?

mattt commented 3 years ago

Your example constructs a dictionary with String keys and AnyEncodable values. Like the compiler error says, you can't put a String value where an AnyEncodable value is expected. The reason string literals work is that AnyEncodable AnyEncodable conforms to ExpressibleByStringLiteral; in this context, string literals result in AnyEncodable values, not String.

You can convert a String to AnyEncodable using string interpolation (as you have in the next line of your example) or through an explicit initializer (AnyEncodable(bar)).