Benjamin,
It sounds like your concern is that people might write objects that just store
everything in a dictionary, instead of declaring typed properties. Correct?
> On Dec 7, 2017, at 7:11 AM, Benjamin G via swift-evolution
> <swift-evolution@swift.org> wrote:
>
> I think i answered that question many times as well (by masquerading
> dictionaries as regular classes), but if what i'm saying is simply impossible
> because of Swift type system even with the new proposal, i'd rather people
> tell it to me than ask the same question over and over..
>
> _______________________________________________
It would be possible, in theory, to write a class that used a dictionary as a
backing store for all its properties under this proposal. However, the
dictionary would have to be typed [String: Any?], and every property access
would be typed Any?. Your code would look like this:
class MyDynamicObject: DynamicMemberLookupProtocol {
var storage: [String: Any?] = [:]
subscript(dynamicMember: String) -> Any? {
get { return storage[dynamicMember] }
set(newValue) { storage[dynamicMember] = newValue }
}
}
let x: MyDynamicObject = ...
// setting properties is easy!
x.name = “Benjamin”
x.age = 3
// using them, though, is hard!
var adults: [String] = []
if x.age as! Int > 18 {
adults.append(x.name as! String)
}
If you decide to create an object that stores everything in an ‘Any’, Swift is
going to force you to use an ‘as’ cast anytime you want to use it. That’s super
annoying.
So yes, it’s possible to create a type that masquerades a dictionary as a
regular class. But the ergonomics of doing so are sufficiently frustrating that
nobody is likely to do so. Swift makes it easy to declare typed variables here,
and the user experience for doing so is vastly improved (code completion,
compile-time checking, no more ‘as’ casting, etc).
So while it’s theoretically possible to do this, I don’t think it’s a concern
in practice. The incentives are already in place to encourage doing the “right”
thing in this case, even with the possibility of dynamic member lookup.
-BJ
_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution