Generic Enums in Swift

Enums in Swift, especially associated values, are incredibly powerful. ReactiveCocoa uses them to model their Event class and Alamofire for their Result class. Generics as well are equally powerful.

However there are some stark limitations. Let's say for example, I'm building a service class to abstract away the different ways of fetching data in my application. The enum to represent a "service" might look like this:

enum Service<T: Object, U: NSManagedObject, V> {
    case Realm(T.Type)
    case CoreData(U.Type, String)
    case Network(V.Type, NSURL, String)
}

and then the enum would have methods such as:

func find(parameters: [String: AnyObject])
func get(id: String)

One would reasonably expect to be able to store these services in some type of manager and later retrieve them:

ServiceManager.services[.Realm(Object.self)]

but because of the generic constraints, T, U, and V have to be known ahead of time and when storing in a dictionary, T, U, and V all have to be of the same type for all the stored enums.

The other problem is in the service methods. With the above example of the find function, it'd be great if the consumer could specify the return model type:

func find<Model>(parameters: [String: AnyObject])->SignalProducer<[Model],  NSError>

However based on the value of the associated enum, the constraints on the generic type Model need to change.

Is there any way to store generic types as a dictionary value? I found a possible workaround, in the class that they're being stored, use typealias to match the constraints.

typealias T = Object
typealias U = NSManagedObject
typealias V = Any

private var registeredServices: [Service<T, U, V>]

which seems to defeat the purpose of having generic constraints in the first place.

And there's no way to in Swift to "optionally require" generic types is there? Something that would roughly look like:

func find<T where self == .Realm || self == .Network || self == .CoreData> ...

In other words there doesn't seem to be a way to apply a set of generic constraints based on the value of the enum itself.

链接地址: http://www.djcxy.com/p/54424.html

上一篇: 无法将整数转换为通用方法中的枚举

下一篇: Swift中的泛型枚举