其實代表們不只是在客觀C.代表團提供可在斯威夫特(任何不涉及的Objective-C的動態特性能夠在斯威夫特)和授權是一種設計模式( delegation as a design pattern),而不是語言實現。您可以使用兩種方法之一,塊/閉包或委派。在迅速代表團的一個例子蘋果的文檔中找到如下參考:
Apple documentation on delegation
您還可以看到在關閉了蘋果的文檔參考這裏: Apple documentation on closures
可以證明代表團的一個例子下面:
注意,委託通過下面的協議宣稱:
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)
}
個
類檢查其是否具有一個委託,如果是這樣,它調用的類必須由符合上述
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
}
}
鏈接給OBJ-C解決方案的協議實現方法,你發現了什麼? – AstroCB 2015-02-06 03:19:42
@AstroCB http://stackoverflow.com/questions/6203799/dismissmodalviewcontroller-and-pass-data-back – JayVDiyk 2015-02-06 03:20:49
@AstroCB http://stackoverflow.com/questions/14468995/passing-data-back-with-multiple-viewcontrollers -using-delegates – JayVDiyk 2015-02-06 03:21:10