简体   繁体   中英

Cannot assign value of type '(_) -> ()' to type '((String, String, String, Int) -> ())?'

I have a closure defined like this,

public var onLogCompletion:((_ printLog:String,_ fileName:String,_ functionName:String,_ lineNumber:Int) -> ())? = nil

Which is updated like this,

fileprivate func printerCompletion(printLog:String, fileName:String, functionName: String, lineNumber:Int) -> Void {
    if onLogCompletion != nil {
        onLogCompletion!(printLog, getFileName(name: fileName), functionName, lineNumber)
    }
}

And using it like this,

    Printer.log.onLogCompletion = { (log) in
        //print(log)
        //print(log.0)
    }

Error:

Cannot assign value of type '(_) -> ()' to type '((String, String, String, Int) -> ())?'

But this is giving me above error and not sure what to do?

The same is working fine with Swift 3.x.

The reason its not working in Swift 4 is because of Distinguish between single-tuple and multiple-argument function types(SE-0110) .

If you still want to work in a way you are doing in Swift 3 than you need to set the function type's argument list to enclosed with Double parentheses like this.

public var onLogCompletion:(((String,String,String,Int)) -> ())? = nil

Now you all set to go

Printer.log.onLogCompletion = { (log) in
    //print(log)
    //print(log.0)
}

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