Swift @escaping について

参考にさせていただきました

Swift 3 の @escaping とは何か - Qiita

クロージャーがスコープを抜けても存在し続けるときに、@escaping が必要になる。

  • クロージャがスコープ外で強参照されるとき
  • クロージャを非同期的に実行するとき

実装例 非同期に実行するときに該当

//1 ボタンの生成タイミング遅らせている
    private lazy var behaviorAsButton = BehaviorAsButton{_ in
   //5
        self.performSegue(withIdentifier: "transforAddress", sender: nil)
    }


   override func viewDidLoad() {
        super.viewDidLoad()
        if scene == .office {
            uiNaviItem.title = NSLocalizedString("ScwOffice", comment: "")
        } else {
            uiNaviItem.title = NSLocalizedString("ScwClient", comment: "")
        }

//定義を設定 このタイミングで2が呼ばれる
        uiAddress.delegate = behaviorAsButton




関数定義

テキストフィールドをタップするとsegueが実行されて、画面が遷移する

class BehaviorAsButton: NSObject, UITextFieldDelegate {
//3
    let action: (UITextField) -> Void
//2- タイミング actionに詰め込まれるまではOK その後別のタイミングで呼び出される キャプチャー
    init(_ action: @escaping (UITextField) -> Void ) {
        self.action = action
    }
//4
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        action(textField)
        return false
    }
}