You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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"letbar:JSON=["a": someJSONString]// all good
c.
let someActualString: String ="b"lettaz:JSON=["a": someActualString]// compiler error: Cannot convert value of type 'String' to expected dictionary value type 'JSON'
The text was updated successfully, but these errors were encountered:
cjmconie
changed the title
JSON initialisation using variables
JSON initialisation using variables of primitive type
Apr 17, 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:
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.)
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
)?The text was updated successfully, but these errors were encountered: