Reputation: 3137
I'm going through the iOS tutorial from Apple developer page.
It seems to me that protocol
and interface
almost have the same functionality.
Are there any differences between the two?
the different usage in the project?
Updated
Yes, I did read the link above and I'm still not sure what the differences and usage between protocol
and interface
. When I ask a question like this, I would like to see a simple explanation about the topic. Sometime it could be tough to get everything from the documentation.
Upvotes: 201
Views: 46256
Reputation: 1751
Essentially protocols are very similar to Java interfaces except for:
protocol<A, B>
way of protocol composition. For example, declaring a function parameter that must adhere to protocol Named
and Aged
as: func wishHappyBirthday(to celebrator: Named & Aged) {}
These are the immediately apparent differences for a Java developer (or at least what I've spotted so far). There's more info here.
Upvotes: 161
Reputation: 1
Just adding one thing because I've been checking protocols combining:
you can combine protocols at any point with the protocol<> keyword.
This is no longer true. Based on this: https://github.com/apple/swift/blob/master/test/type/protocol_composition.swift
This is correct:
func foo ( var1 : A & B ){}
Upvotes: 0
Reputation: 3157
Complementing @Thomas Schar's answer. The Swift protocol magic comes from the extension.
One thing that got me scratching my head for a couple of hours is that not all protocols can be used as property types. For example, if you have a protocol with typealias, you cannot directly use it as a type of property (it makes sense when you think about it, but coming from Java we really want to have a property like userDao: IDao).
Upvotes: 36