[swift-evolution] [Pitch] Generic associatedtype subtype constraints
Rex Fenley
rex at remind101.com
Tue Oct 24 13:51:54 CDT 2017
Currently you can constrain a type parameter via a generic using equality
protocol A {
associatedtype T where T == BKind.V
associatedtype BKind: B
}
protocol B {
associatedtype V
}
However, you cannot do the following
associatedtype T where T: BKind.V
Could this be added to the language? Is there a reason something like this
would not be sound?
My use case would look like the following
protocol Mapping {
associatedtype MappedObject: DatabaseAdapterKind.BaseType
associatedtype DatabaseAdapterKind: DatabaseAdapter
...
}
protocol DatabaseAdapter {
associatedtype BaseType
...
}
For Realm Obj-C fulfillment would look like the following
// User is an RLMObject subtype
protocol UserMapping: Mapping {
typealias MappedObject = User
typealias DatabaseAdapterKind = RealmAdapter
// ... functions
}
protocol RealmAdapter: DatabaseAdapter {
typealias BaseType = RLMObject
// ... functions
}
For CoreData replace RLMObject with NSManagedObject
The mapping system allows the developer to write a mapping from JSON to a
type (MappedObject). Given that the type of MappedObject is a subtype of
the BaseType of the DatabaseAdapter the system will write an object of type
MappedObject to the database. This setup works with Realm Obj-C,
RealmSwift, and Core Data all of which have different BaseTypes but use
subtyping from a BaseType to specify the Model/MappedObject that is stored
in the db.
I can't use MappedObject == DatabaseAdapterKind.BaseType because this needs
to be a subtyping relation. E.g. a User: NSManagedObject is true but User
== NSManagedObject is not.
Since I can't specify this subtype relation in the protocol I end up having
to do runtime type checking and as! casts in quite a few places which seems
unnecessary and error prone during refactoring.
--
Rex Fenley | IOS DEVELOPER
Remind.com <https://www.remind.com/> | BLOG <http://blog.remind.com/>
| FOLLOW
US <https://twitter.com/remindhq> | LIKE US
<https://www.facebook.com/remindhq>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20171024/cd9648a1/attachment.html>
More information about the swift-evolution
mailing list