swift - Call a static func on optional type -


i have protocol, conforming class , class 1 simple function.

protocol outputable {     static func output() }  class foo: outputable {     static func output() {         print("output")     } }  class bar {     func eat(_ object: anyobject?) {         if let object = object, let objecttype = type(of: object) as? outputable.type {             objecttype.output()         }     } }  let foo = foo() let bar = bar() var foooptional: foo? bar.eat(foo) // prints 'output' bar.eat(foooptional) // print nothing 

is there way pass optional type being nil conforming outputable protocol , call protocol's static functions inside eat function? though it's nil still passing type , that's should need inside eat, right?

to make more clear. know why last line prints nothing. there way adjust eat print 'output' string out?

one of way achieve you're seeking use generics , call method on type:

func eat<t: outputable>(_ object: t?) {     t.output() } 

this work both foo , foo?


Comments

Popular posts from this blog

html - How to set bootstrap input responsive width? -

javascript - Highchart x and y axes data from json -

javascript - Get js console.log as python variable in QWebView pyqt -