Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Swift Generic Downcast Question
protocol BaseProtocol {
func doIt()
}
protocol DerivedProtocol : BaseProtocol {
func hello()
}
class MyObject: DerivedProtocol {
func doIt() { print("doIt") }
func hello() { print("hello") }
}
let o = MyObject()
// BTW: I do not want `func workOnDerived(value: DerivedProtocol)` here,
// this is supposed to receive the full type `T` from workOnBase.
func workOnDerived<T: DerivedProtocol>(value: T) {
value.hello()
}
func workOnBase<T: BaseProtocol>(value: T) {
// the compiler still has the full type T here,
// i.e. T is `MyObject`
if value is DerivedProtocol {
// how can I call workOnDerived(value)?
// or in other words, how to I downcast the protocol
// requirement?
workOnDerived(value: value) // how??
}
else { fatalError("unexpected") }
}
workOnBase(value: o) // entry point, cannot control this
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment