Skip to content

Instantly share code, notes, and snippets.

@helje5
Last active February 11, 2018 10:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save helje5/a3c26a63092a57dd61f5a1dcb7c8580e to your computer and use it in GitHub Desktop.
Save helje5/a3c26a63092a57dd61f5a1dcb7c8580e to your computer and use it in GitHub Desktop.
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