Based on recently active topics such as Tuples conform to Equatable and Anonymous Structs, I'd like to throw my own pre-pitch onto the table as well: as struct
syntax.
It's common for libraries to support functions that accept arbitrary dictionaries, one example being serializers:
func serialize(_ dictionary: [String: Any]) { ... }
serialize(
[
"name": "John Doe",
"age": 40,
"favoriteMeals": {
"breakfast": "scrambled eggs",
"lunch": "reuben",
"dinner": "carbonara"
}
]
)
This approach has several problems:
- There's no clean way to enforce at compile-time that that the given dictionary is actually serializable. JSONSerialization performs this check at run-time, and
Encodable
requires employing type-erasure. - Similarly, this approach makes you prone to duplicate keys, something one would either have to explicitly check at run-time, or allow to pass through undetected.
With these issues in mind, I propose new syntactical sugar that enables a tuple declaration to be instantiated as an anonymous struct. For example:
let myValue = (foo: "bar", one: 1, true) as struct
print(myValue.foo) // "bar"
print(myValue.2) // "true"
would desugar into
struct __some_struct {
var foo: String
var one: String
var _2: Bool
}
let myValue = __some_struct(foo: "bar", one: 1, _2: true)
print(myValue.foo) // "bar"
print(myValue._2) // "true"
This would also support limited protocol conformance, transforming the earlier example into something like:
func serialize<T: Encodable>(_ value: T) { ... }
serialize(
(
name: "John Doe",
age: 40,
favoriteMeals: (
breakfast: "scrambled eggs",
lunch: "reuben",
dinner: "carbonara"
) as Encodable struct
) as Encodable struct
)
Clearly, this pitch is still quite rough, but I'd love to get feedback from folks here, especially on any language design shortcomings I'm likely missing.