user3467312
user3467312

Reputation: 69

Swift: conforming to protocol using extension and composition pattern

On slide 62 in this PDF: Some Columbia College Presentation it says that one of the ideas behind Swift and its extensions was to conform to protocols using the composition pattern.

Now I understand the syntax for extensions in Swift

//example from Apple:
extension SomeType: SomeProtocol, AnotherProtocol {
// implementations of not yet provided functions and properties of SomeType go here
}

But what does the composition pattern have to do with it? The guy did mean the composite pattern described here, right? Can someone please provide a minimal example how it is used?

Upvotes: 1

Views: 529

Answers (1)

luk2302
luk2302

Reputation: 57124

Composition refers to "implementing" interfaces, in Swift called conforming to protocols.

On the other side of the fence is Inheritance where you extend classes.

The main problem here is that you can only extend one class but conform to as many interfaces as you wish (at least in Swift). Therefore if your class wants to be the UITableViewDelegate and UITableViewDataSource you can only achieve that with composition.

Interfaces/Protocols leave a lot more open to the developer in opposition to what classes can you. Protocols only define functions and methods - and in Swift properties, which have some function-like functionality themselves. Classes on the other hand can contain variables, constants etc. And they can implement some of them already - something that interfaces mostly cannot do.

Upvotes: 2

Related Questions