Define the stopHandler closure inside the function showAlert()and it should work.
class ViewController: UIViewController
{
var icnNum : Int64 = 0
func showAlert( userStatus: String ) {
let stopHandler = { (action:UIAlertAction!) -> Void in
let num = self.icnNum
}
let alert = UIAlertController(title: "", message: "", preferredStyle: .Alert)
alert.title = "What you want to do?"
alert.addAction(UIAlertAction(title: "Stop", style: .Default, handler: stopHandler))
}
}
}
The compiler will force you to write self.icnNuminstead icnNum, so that it is obvious that the closure will contain a reference to self.
stopHandler , , . ViewController stopHandler, self ( ViewController).
, stopHandler
class ViewController: UIViewController {
var icnNum : Int64 = 0
var stopHandler: ((action:UIAlertAction!) -> Void)?
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
self.stopHandler = { [weak self] (action:UIAlertAction!) -> Void in
let num = self?.icnNum
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func showAlert( userStatus: String )
{
let alert = UIAlertController(title: "", message: "", preferredStyle: .Alert)
alert.title = "What you want to do?"
alert.addAction(UIAlertAction(title: "Stop", style: .Default, handler: stopHandler))
}
}
[weak self] stopHandler. , , .
: https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/AutomaticReferenceCounting.html#//apple_ref/doc/uid/TP40014097-CH20-ID57