使用 Swift 从弹出的 ViewController 传回数据 [英] Pass data back from a popped ViewController using Swift
问题描述
我想知道我们如何从弹出的 ViewController 传回数据
I would like to know how do we pass a data back from a popped ViewController
FirstViewController -----push----> SecondViewController
SecondViewController -----popped(Pass Value?) ----> FirstViewController
我已经搜索并找到了许多要求使用委托的解决方案,但这些都在我不熟悉的 Objective C 中.
I have searched around and found many solutions asking to use delegates, but those are in Objective C which I am not familiar with.
我们如何在 Swift 中做到这一点?
How do we do this in Swift?
谢谢
推荐答案
实际上委托不仅仅在 Objective C 中可用.委托在 Swift 中可用(任何不涉及 Objective-C 的动态特性的都可以在 Swift 中使用)委托是一种设计模式(委托作为一种设计模式),而不是一种语言实现.您可以使用两种方法之一,块/闭包或委托.可以在此处引用的 Apple 文档中找到 swift 中的委派示例:
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 关于闭包的文档的参考:关于闭包的 Apple 文档
You may also see references for Apple's documentation on closures here: Apple documentation on closures
委托示例如下所示:
请注意,委托是通过以下协议声明的:
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
}
}
这篇关于使用 Swift 从弹出的 ViewController 传回数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!