templates - Implementing generic interfaces in Apple's Swift -
i have class property should have type in other languages called generic (or template) interface. when try mimic behavior in swift cannot protocols work idea. example:
protocol p { typealias t func returnt() -> t } class g<t>: p { var t: t init(t: t) { self.t = t } func returnt() -> t { return t } } class c { var p: p<int> // cannot specialize non-generic type 'p' init(instanceofp: p<int>) { // cannot specialize non-generic type 'p' p = instanceofp } func usepst() -> int { return p.returnt() // 'p' not have member named 'returnt' } }
errors compiler reported comments. seems clear me such situation should not problematic: since swift's protocols cannot generics (they use obscure typealias
syntax instead) c
has no way know every class implements p
can specialized int
. there swift-y way represent situation correctly? or there known workaround don't have force or de-generalize class structure?
the generic isn't needed in protocol (use any
) - it's needed in class g<t>
. this...
protocol p { func returnt() -> } class g<t>: p { var t: t init(t: t) { self.t = t } func returnt() -> { return t } } class c { var p: p init(instanceofp: p) { p = instanceofp } func usepst() -> { return p.returnt() } } let gi = g<int>(t: 7) // {t 7} let ci = c(instanceofp: gi) // {{t 7}} ci.usepst() // 7 let gs = g<string>(t: "hello") let cs = c(instanceofp: gs) cs.usepst() // "hello"
Comments
Post a Comment