Contents

Swift supports optional protocol via @objc keyword, like OPTIONAL PROTOCOL

1
2
3
4
5
@objc protocol OptionalProtocol {
optional func optionalMethod() // Optional
func necessaryMethod() // Required
optional func anotherOptionalMethod() // Optional
}

If there’s Enum, Tuple (which are not available in Objective C) in your protocol methods, then this @objc trick does not work

Luckily, Swift 2 supports Protocol Extension, which we can use to provide default implementation. So the conformance only has to implement the methods that it truly needs

Take a look at PlayerDelegate in my Cine

You need to mark your protocol extension public in order for your consumer to use it

PlayerDelegate.swift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public protocol PlayerDelegate : class {
func player(player: Player, didChangeStatus status: Status)
func player(player: Player, didChangePlaybackState state: PlaybackState)
func player(player: Player, didChangeLoadState state: LoadState)

func player(player: Player, didFinishWithResult: Result)

func playerDidChangeCurrentItem(player: Player)
func playerDidLoadDuration(player: Player)
func playerDidTick(player: Player)

func playerDidBeginSeeking(player: Player)
func playerDidEndSeeking(player: Player)
}

public extension PlayerDelegate {
func player(player: Player, didChangeStatus status: Status) {}
func player(player: Player, didChangePlaybackState state: PlaybackState) {}
func player(player: Player, didChangeLoadState state: LoadState) {}

func player(player: Player, didFinishWithResult: Result) {}

func playerDidChangeCurrentItem(player: Player) {}
func playerDidLoadDuration(player: Player) {}
func playerDidTick(player: Player) {}

func playerDidBeginSeeking(player: Player) {}
func playerDidEndSeeking(player: Player) {}
}

Contents