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

networking - Vagrant-provisioned VirtualBox VM is not reachable from Ubuntu host -

c# - ASP.NET Core - There is already an object named 'AspNetRoles' in the database -

ruby on rails - ArgumentError: Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true -