简体   繁体   English

Swift 构建错误:闭包捕获列表中的预期名称

[英]Swift build error: Expected name of in closure capture list

I'm pretty new to Swift.我对 Swift 很陌生。

I'd love to show dynamic text in a TextView with this code我很想用这个代码在 TextView 中显示动态文本

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var m_logView: UITextView!

    private let m_log = Log()
    override func viewDidLoad() {
        super.viewDidLoad()
        addLog(msg: "Hello World!")
        m_log.requestData{ [weak, self] (data: String) in   // ### Build error points at this line!
            self.useData(log: data)
        }
    }

    func useData(log: String) {
        addLog(msg: log)
    }

    func addLog(msg: String) {
        m_logView.text += msg + "\n"
    }
}

class Log {
    func requestData(completion: (_ data: String) -> Void) {
        let data = "Data from wherever"
        completion(data)
    }
}

But I got a compiler error:但我得到一个编译器错误:

Expected name of in closure capture list

What does it mean and how to fix this?这是什么意思以及如何解决这个问题?

This is silly TYPO mistake on [weak, self]这是[weak, self]上的愚蠢 TYPO 错误

Replace your code with将您的代码替换为

m_log.requestData{ [weak self] (data: String) in   
    self?.useData(log: data)
}

and as you have used weak self , You may use self?并且由于您使用了weak self ,您可以使用self 吗? or unwrap it with guard let or if let或者用guard let或者if let打开它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM