generics - Call Class Methods From Protocol As Parameter -
i want able pass class (not initialized object) of protocol type method, call class functions of class in method. code below.
i using swift , have protocol defined this
//protocol object used fauapiconnection protocol fauapimodel{ //used parse object given dictionary object class func parsefromjson(json:anyobject) -> self //required default init init() }
what have method this
func getsomeparsingdone<t:fauapimodel>(model:t.type? = nil, getpath:path, callingobj:callingclass) -> void { //getit inconsequential, logic object path var returnobj:anyobject = getit.get(path) if(model != nil){ returnobj = model!.parsefromjson() <<<<<< type 't' not conform protocol 'anyobject' } callingobj.done(returnobj) }
object implements protocol
import foundation class myobj: fauapimodel{ var neededval:string var nonneededval:string required convenience init(){ self.init(neededval:"value") } init(neededval:string, nonneededval:string = ""){ self.neededval = neededval self.nonneededval = nonneededval } class func parsefromjson(json:anyobject) -> wgmpart { return wgmpart() <<<<<<<< method 'parsefromjson' in non-final class 'wgmpart' must return 'self' conform protocol 'fauapimodel' } }
however, keep getting 2 errors. have indicated these above '<<<<<<<<<<<<'
compile error.
lots of little things consider here, let's heart of question. signature want looks this:
func getsomeparsingdone<t:fauapimodel>(model:t.type, path:string) -> t?
i'm making return optional beause there lot of things fail here, , shouldn't turn of crashes.
i'd recommend protocol this:
protocol fauapimodel { class func parsefromjson(json:anyobject) -> self }
that way, you're promising return own class, not parseable. tend mean need make classes final
. if don't want them final
, you'll need promise init
method in order construct it. see protocol func returning self more details on how deal if need it.
so putting together, might in practice:
protocol fauapimodel { class func parsefromjson(json:anyobject) -> self } func createobjectofclass<t: fauapimodel>(model: t.type, path: string) -> t? { if let json: anyobject = getjson(path) { return model.parsefromjson(json) } return nil } // bogus json reader func getjson(path: string) -> anyobject? { let json: anyobject? = nsjsonserialization.jsonobjectwithdata(path.datausingencoding(nsutf8stringencoding, allowlossyconversion: true)!, options: nsjsonreadingoptions(0), error: nil) return json } // bogus model class returns trivial version of final class something: fauapimodel { class func parsefromjson(json:anyobject) -> { return something() } } // using let = createobjectofclass(something.self, "/path/to/file")
Comments
Post a Comment