Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JSON initialisation using variables of primitive type #24

Closed
cjmconie opened this issue Apr 17, 2019 · 2 comments
Closed

JSON initialisation using variables of primitive type #24

cjmconie opened this issue Apr 17, 2019 · 2 comments
Assignees

Comments

@cjmconie
Copy link
Collaborator

When trying to initialise a JSON type, why would the compiler be happy with a literal string (e.g. "b"), but unhappy with a variable with a type of String (e.g. someActualString )?

a.
let foo: JSON = ["a": "b"]   // all good

b.
let someJSONString: JSON = "b"
let bar: JSON = ["a": someJSONString] // all good

c.
let someActualString: String = "b"
let taz: JSON = ["a": someActualString] // compiler error: Cannot convert value of type 'String' to expected dictionary value type 'JSON'
@cjmconie cjmconie changed the title JSON initialisation using variables JSON initialisation using variables of primitive type Apr 17, 2019
@zoul
Copy link
Collaborator

zoul commented Apr 18, 2019

This is how ExpressibleByXXXLiteral (ExpressibleByDictionaryLiteral, ExpressibleByStringLiteral, …) works in Swift.

In the first case the compiler sees a variable foo of type JSON initialized by a dictionary literal. That doesn‘t typecheck directly, but then the compiler notices that the left-hand type (JSON) conforms to ExpressibleByDictionaryLiteral, and so it offers the following initializer:

init(dictionaryLiteral elements: (String, JSON)...)

And that’s how the compiler can create a value of JSON type from a dictionary. Your second case works the same way, just using the ExpressibleByStringLiteral protocol and a different initializer:

init(stringLiteral value: String)

(These all are visible in the Initialization.swift file.)

But this machinery only works for literals, not variables, and that’s why your third example won’t compile – it’s not a literal. (If the ExpressibleByXXXLiteral machinery worked for variables, too, it would be a nightmare I guess, since you could get a lot of non-obvious automatic conversions.)

Does that make sense?

@zoul zoul self-assigned this Apr 23, 2019
@cjmconie
Copy link
Collaborator Author

OK, thanks for the explanation. Makes sense.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants