Reputation: 309
I'm wondering whether this kind of function definition is possible in swift
Let's say we have this 3 protocols
protocol Foo {
typealias T
func get(key: String) -> T
}
protocol Bar {
typealias T: Cacheable
func set(item: T)
}
protocol Cacheable: NSCoding {
func getKey() -> String
}
Then this two classes
class MyClass<T: Cacheable>: Foo, Bar { ... }
class MyOtherClass<T: Cacheable>: Foo, Bar { ... }
Imagine that we want a function that can receive an instance of either one of this classes. I can not figure out how to get the signature right, I have tried this that seems logical but it does not work
func doThing<T<V> : protocol<Foo, Bar> where V:Cacheable>(instance: T) { ... }
Any clue?
Thanks!
Upvotes: 1
Views: 587
Reputation: 40965
You want to put a constraint on the placeholder based on its associated type:
func doThing
<U: protocol<Foo, Bar> where U.T: Cacheable>
(instance: U) {
// ...
}
(You also probably want to avoid giving associated types the name T
– that’s best left just for placeholders – in theory you could write T where T.T: Cacheable
but its likely to lead to some horrible confusion at some point. If this is a container, the convention is Element
)
Upvotes: 2