Honey Honey - 1 month ago 5x
Objective-C Question

Swift vs Objcective-C protocols

Coming from an Objective-C background where every protocol must always have a delegate property. In Swift that doesn't seem to be the case and it's breaking the paradigm I have had about protocols.

AFAIK in Swift, protocols are used for 2 major purposes: delegation pattern (which would need a delegate like Objective-C) and also composition pattern (that didn't exist in Objective-C and doesn't need a delegate property) coupled with extension making it more effective than the traditional inheritance pattern in Objective-C.

Have I understood correctly? Can you please clarify?


What I mean by what I see different is:
From Apple's WWDC

The traditional way is (Slide76):

class Ordered {
func precedes(other: Ordered) -> Bool { fatalError("implement me!") }
class Number : Ordered {
var value: Double = 0
override func precedes(other: Ordered) -> Bool {
return self.value < (other as! Number).value

The new Swift way is (Slide 90):

protocol Ordered {
func precedes(other: Self) -> Bool
struct Number : Ordered {
var value: Double = 0
func precedes(other: Number) -> Bool {
return self.value < other.value

And I have never seen Protocols being used like this in Objective-C. So how are they different?


Both in Objective-C and in Swift, protocols have exactly one purpose: to allow arbitrary or unrelated types to be guaranteed of having certain members (or, in the case of optional members, of at least possibly having those members). In particular, this guarantee is important to the compiler. Basically, then, a protocol is a sort of pseudo-type that overlays the real type structure and unites it in new ways (instead of, say, the "mixin" employed for the same purpose by some other languages; Ruby, for example, doesn't need protocols because it has modules).

For example, a Bird and an Insect may be unrelated classes, or even (in Swift) not classes at all, but if they both adopt the Flier protocol which requires a fly() method, the compiler knows that they can both fly, and will allow the fly() message to be sent to a Bird or an Insect.

The fact that protocols can be used in various common and important architectural patterns, such as delegation, is a purely secondary but very natural consequence of the nature of protocols.