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

python - What's the Pythonic way to report nonfatal errors in a parser? -

sql server - Deadlock occuring in Clustered Columnstore index -

php - curl: (35) OpenSSL SSL_connect: SSL_ERROR_SYSCALL in connection to domain.com:443 -