很简单,我肯定我漏掉了什么。
我试图理解如何实现以下目标:action
应该“保存”一块代码,我最终将在UIView.animate
内部执行(例如)。
什么是正确的方法?+我是否应该担心使用self.
在action
闭包内的保留周期?
示例函数:
func forward(_ sender : UIButton) {
var action : <Clousre of somekind?>
switch currentPosition
{
case 0 : action = { self.view.background = .red }
case 1 : action = { self.view.background = .blue }
default : fatalError("No current Position")
}
UIView.animate(withDuration: 1, animations: {
action
})
}
谢谢!:)
最佳答案
声明如下:
var action: () -> Void
没有保留周期。
self
不包含对action
的引用。如果
action
是一个属性(在函数之外),则会有一个保留周期:self.action
action = { self... }
总括起来:
var action : () -> Void
switch currentPosition {
case 0 : action = { /*do something*/ }
case 1 : action = { /*do something*/ }
default : fatalError("No current Position")
}
UIView.animate(withDuration: 1, animations: {
action()
})
// or
UIView.animate(withDuration: 1, animations: action)
(在操场上编辑)
关于swift - 在变量内部存储代码块,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41066978/