Last active
February 11, 2018 10:20
-
-
Save helje5/a3c26a63092a57dd61f5a1dcb7c8580e to your computer and use it in GitHub Desktop.
Swift Generic Downcast Question
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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