chevron-up bell reply instagram twitter2 feed3 finder search-25px-p0

Delegation in Swift

2017-04-27

Similarly, in Swift you can have Delegation:

Step 1: Create a new Cocoa class, i.e WeatherService.swift, in this Swift file which include:

  • A Protocol
  • A Delegate Property

WeatherService.swift

[gist https://gist.github.com/arkilis/5158db538c985612506af43d7e9f77c8/]

Step 2: Implement Delegation

[gist https://gist.github.com/arkilis/83a381aeb29592e44c6dc502343176ae/]


There are a couple of things have to pay attention to:

  • As Swift support multi-inherence, which means a class can inherit from more than one class. So you can implement your Swift Delegation like the one in the above. However, you can also make use of the extension keyword, as shown in above code way 2.
  • By default, protocol methods are compulsory in Swift which is DIFFERENT from Objective-C (which is Optional, gives out warning if they are not implemented)

arkilis

Comments: