Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I simulate traits/mixins in Swift?

Does Swift have a way of mixing in traits, a la Scala? The section of the Swift book on using extensions to add protocols to existing classes comes tantalizingly close. However, since protocols can't contain an implementation, this can't be used to mix code into a class. Is there another way?

like image 840
Bill Avatar asked Jun 08 '14 15:06

Bill


1 Answers

As of Swift 2.0, yes!

Providing Default Implementations

You can use protocol extensions to provide a default implementation to any method or property requirement of that protocol. If a conforming type provides its own implementation of a required method or property, that implementation will be used instead of the one provided by the extension.

like image 173
Jessy Avatar answered Oct 13 '22 19:10

Jessy