polymorphism - polymorphic methods that return different class types in Swift? -


i have collection of heterogeneous object types (common superclass). per element, want fetch class type instantiate. in objectivec, did this:

@implementation commonclass - (class) secondaryannotationclass {     return [mkannotationview class]; // abstract implementation, return default class } @end @implementation subclassfoo - (class) secondaryannotationclass {     return [fooannotationview class]; // specific annotation class } @end @implementation subclassbar - (class) secondaryannotationclass {     return [barannotationview class]; // specific annotation class } @end 

so do recreate in swift? think it's following, haven't yet done right thing make compiler take easy red dots away.

class commonclass {     var secondaryannotationclass:type {         return mkannotationview.self // abstract implementation, return default class     } } class subclassfoo:commonclass {     var secondaryannotationclass:type {         return fooannotationview.self // specific annotation class     } } class subclassbar:commonclass {     var secondaryannotationclass:type {         return barannotationview.self // specific annotation class     } } 

it seems keep swift's type system happy, need i'll return not type (is replacement class?), mkannotationview or 1 of subclasses.

you have secondaryannotationclass return mkannotationview.type:

class commonclass {     var secondaryannotationclass: mkannotationview.type {         return mkannotationview.self     } }  class subclassfoo:commonclass {     override var secondaryannotationclass: mkannotationview.type {         return fooannotationview.self     } }  class subclassbar:commonclass {     override var secondaryannotationclass: mkannotationview.type {         return barannotationview.self     } } 

with approach, if have methods or properties specific fooannotationview or barannotationview need use, you'll have downcast. example:

class fooannotationview: mkannotationview {     func myfunc() {         print("foo")     } }  let subclassfoo = subclassfoo() let annotation = subclassfoo.secondaryannotationclass() as! fooannotationview annotation.myfunc() // prints: "foo" 

Comments

Popular posts from this blog

javascript - gulp-nodemon - nodejs restart after file change - Error: listen EADDRINUSE events.js:85 -

Fatal Python error: Py_Initialize: unable to load the file system codec. ImportError: No module named 'encodings' -

javascript - oscilloscope of speaker input stops rendering after a few seconds -