简体   繁体   中英

Swift build error: Expected name of in closure capture list

I'm pretty new to Swift.

I'd love to show dynamic text in a TextView with this code

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]

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? or unwrap it with guard let or if let

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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