Swift: Providing a default protocol implementation in a protocol extension -


i'm trying play around bit swift, protocols , protocol extensions. i'm trying provide default implementation of protocol in protocol extension. code:

protocol proto : class {     func somemethod() -> string }  extension proto {     static func create() -> self {         return protodefaultimpl() as! self     } }  class protodefaultimpl : proto {     func somemethod() -> string {         return "doing something"     } }  let instance = proto.create() let output = instance.somemethod()  print(output) 

the compiler complains on line call proto.create(), following error: error: static member 'create' cannot used on instance of type 'proto.protocol'.

have missed here? there way can achieve this?

thanks.

you can't call method on protocol itself, have call on type implements protocol. doesn't change because there default implementation of protocol in extension. change type proto protodefaultimpl , work expect.

protocol proto : class {     func somemethod() -> string }  extension proto {     static func create() -> self {         return protodefaultimpl() as! self     } }  class protodefaultimpl : proto {     func somemethod() -> string {         return "doing something"     } }  let instance = protodefaultimpl.create() let output = instance.somemethod()  print(output) 

this outputs: doing something


Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

How to get the ip address of VM and use it to configure SSH connection dynamically in Ansible -

javascript - Get parameter of GET request -