Actually delegates are not just available in Objective C. Delegation is available in Swift (anything that does not involve the dynamic nature of Objective-C is able in Swift) and delegation is a design pattern (delegation as a design pattern), not a language implementation. You can use one of two methodologies, blocks/closures, or delegation. An example of delegation in swift can be found in Apple's documentation as referenced here:
Apple documentation on delegation
You may also see references for Apple's documentation on closures here:
Apple documentation on closures
An example of delegation can be shown below:
Noted that the delegate is declared via the protocol below:
protocol DiceGame {
var dice: Dice { get }
func play()
}
protocol DiceGameDelegate {
func gameDidStart(game: DiceGame)
func game(game: DiceGame, didStartNewTurnWithDiceRoll diceRoll: Int)
func gameDidEnd(game: DiceGame)
}
The class checks if it has a delegate, if it does, it calls the methods the class must implement by conforming to the protocol above
class SnakesAndLadders: DiceGame {
let finalSquare = 25
let dice = Dice(sides: 6, generator: LinearCongruentialGenerator())
var square = 0
var board: [Int]
init() {
board = [Int](count: finalSquare + 1, repeatedValue: 0)
board[03] = +08; board[06] = +11; board[09] = +09; board[10] = +02
board[14] = -10; board[19] = -11; board[22] = -02; board[24] = -08
}
var delegate: DiceGameDelegate?
func play() {
square = 0
delegate?.gameDidStart(self)//Calls the method gameDidEnd on the delegate passing self as a parameter
gameLoop: while square != finalSquare {
let diceRoll = dice.roll()
delegate?.game(self, didStartNewTurnWithDiceRoll: diceRoll)
switch square + diceRoll {
case finalSquare:
break gameLoop
case let newSquare where newSquare > finalSquare:
continue gameLoop
default:
square += diceRoll
square += board[square]
}
}
delegate?.gameDidEnd(self)//Calls the method gameDidEnd on the delegate passing self as a parameter
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…