【发布时间】:2018-08-06 08:46:11
【问题描述】:
我有以下代码(编辑:更新了代码,以便每个人都可以编译并查看):
import UIKit
struct Action
{
let text: String
let handler: (() -> Void)?
}
class AlertView : UIView
{
init(actions: [Action]) {
super.init(frame: .zero)
for action in actions {
// let actionButton = ActionButton(type: .custom)
// actionButton.title = action.title
// actionButton.handler = action.handler
// addSubview(actionButton)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class TextAlertView : AlertView
{
init() {
super.init(actions: [
Action(text: "No", handler: nil),
Action(text: "Yes", handler: { [weak self] in
//use self in here..
})
])
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class MyViewController : UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let alert = TextAlertView()
view.addSubview(alert)
self.view = view
}
}
每次我实例化 TextAlertView 时,它都会在 super.init 上崩溃,并且访问权限不正确。但是,如果我改变:
Action(title: "Yes", { [weak self] in
//use self in here..
})
到:
Action(title: "Yes", {
//Blank.. doesn't reference `self` in any way (weak, unowned, etc)
})
有效!
有没有办法在超级初始化期间引用self 在动作块内是否弱(在上面我在super.init 的参数中执行它?
代码编译..它只是在运行时随机崩溃。
【问题讨论】:
-
会不会是因为 Action 是一个结构体?
-
@MikeTaverne;我只是尝试将其设为
class而不是struct.. 同样的问题。我更新了代码,以便我们可以通过 Playground 或常规应用程序编译它并查看。 -
这是一个非常可怕的错误,在调用
self之前,您不应该能够捕获super.init- 虽然它已在最新的 Swift 4.1 快照中修复,但您将获得预期的“' self' 在 'super.init' 调用之前使用”错误。
标签: swift closures swift4 initializer