I have the following code ( EDIT: Updated code so everyone can compile and see it ):
import UIKit
struct Action
{
let text: String
let handler: (() -> Void)?
}
class AlertView : UIView
{
init(actions: [Action]) {
super.init(frame: .zero)
for action in actions {
}
}
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
})
])
}
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
}
}
Every time I create an instance TextAlertView, it crashes super.initwith bad access. However, if I changed:
Action(title: "Yes", { [weak self] in
})
at
Action(title: "Yes", {
})
it works!
Is there a way to refer to selfbeing weak or not inside the action block during super-initialization (in the above example, am I doing this in a parameter super.init?
The code compiles .. it just crashes accidentally at runtime.
source
share