通过闭包内的闭包捕获参数

时间:2019-06-06 14:32:33

标签: swift syntax

在viewDidLoad中,我希望textView被闭包弱捕获,但是我收到错误消息'表达式类型是模棱两可的,没有更多上下文”错误。

import UIKit

final class TableViewCell: UITableViewCell  {

    @IBOutlet weak var textView: UITextView!

}

final class TableViewManager: NSObject, UITableViewDataSource, UITextViewDelegate {

    typealias Action = (UITextView, IndexPath) -> Void

    var action: Action?

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCellID", for: indexPath) as! TableViewCell
        cell.textView.delegate = self
        cell.textView.tag = indexPath.row
        return cell
    }

    func textViewDidBeginEditing(_ textView: UITextView) {
        let indexPath = IndexPath(row: textView.tag, section: 0)
        action?(textView, indexPath)
    }
}

class ViewController: UIViewController {

    private let tableManager = TableViewManager()

    @IBOutlet weak var tableView: UITableView! {
        didSet {
            tableView.dataSource = tableManager
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        tableManager.action = { [weak self] textView, indexPath in
            asyncAfter(seconds: 0.5) { [weak textView] in // error here
                let isFirstResponder = textView?.isFirstResponder ?? false
                if isFirstResponder  {
                    self?.tableView.scrollToRow(at: indexPath, at: .top, animated: true)
                }
            }
        }
    }
}

func asyncAfter(seconds: Double, block: @escaping () -> Void) {
    DispatchQueue.main.asyncAfter(deadline: .now() + seconds, execute: block)
}

如果我删除[weak textView]时错误消失了,但是确定闭包中捕获了textView呢?

0 个答案:

没有答案