Protocols and Extensions

Protocols

Adopting a protocol is like signing a contract to implement every method on the list.

import UIKit

protocol Souschef {
	func chop(vegetable: String) -> String
	func rinse(vegetable: String) -> String
}

class Roommate: Souschef {
	var hungry = true
	var name: String

	init(hungry:Bool, name: String){
		self.hungry = hungry
		self.name = name
	}

	func chop(vegetable: String) -> String {
		return "She's choppin' \(vegetable)!"
	}

	func rinse(vegetable: String) -> String {
		return "The \(vegetable) is so fresh and so clean"
	}
}
class DinnerCrew {
	var members: [Souschef]

	init(members: [Souschef]){
		self.members = members
	}
}
protocol DirtyDeeds {
	func cheat()
	func steal()
}

class Minion: DirtyDeeds {
	var name: String

	init(name:String){
		self.name = name
	}

	func cheat(){
		println("Mwa haha!")
	}

	func steal(){
		println("Mwa haha!")
	}
}

class DinnerCrew {
	var members: [Souschef]

	init(members: [Souschef]){
		self.members = members
	}
}

protocol Souschef {
	func chop(vegetable: String) -> String
	func rinse(vegetable: String) -> String
}

var deviousDinnerCrew = DinnerCrew(members: [Minion]())

Andrew Bancroft’s Swift blog
http://www.andrewcbancroft.com/