我想知道如何从弹出的ViewController传回数据
FirstViewController -----push----> SecondViewController
SecondViewController -----popped(Pass Value?) ----> FirstViewController
我已经四处寻找并找到了许多要求使用代表的解决方案,但那些是在我不熟悉的Objective C中。
我们如何在Swift中执行此操作?
谢谢
答案 0 :(得分:1)
实际上代表不仅仅是目标C中的代表。在Swift中可以使用委托(任何不涉及Objective-C的动态特性的东西都可以在Swift中使用),委托是一种设计模式(delegation as a design pattern),不是语言实现。您可以使用两种方法之一,块/闭包或委派。可以在Apple的文档中找到swift委派的示例:
Apple documentation on delegation
您可能还会在此处看到有关闭包的Apple文档的参考资料: 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
}
}