Swift Question

(WP/S)ZipArchive progress/completion handler type in Swift

I'm trying to use the ZIP library WPZipArchive which is a fork of ZipArchive aka SZipArchive but I have a problem with the

unzipFileAtPath:toDestination:overwrite:password:progressHandler:completionHandler
(phew) function.
WPZipArchive.h#L35-L40

I'm programming in Swift and I have a problem with writing the handlers for the progress and completion handlers

e.g. how to create the
((String!, unz_file_info, Int, Int)->Void)!
handler?

Some attempts:

WPZipArchive.unzipFileAtPath(help, toDestination: temp, progressHandler: (entry:String!, info:unz_file_info, current:Int, total:Int) {
}){ (path:String!, succeeded:Bool, error:NSError!) in
}


with an error


.../ViewController.swift:45:142: Cannot convert value of type '() ->
()' to expected argument type '(entry: String!, info: unz_file_info,
current: Int, total: Int)' (aka '(entry:
ImplicitlyUnwrappedOptional, info: unz_file_info_s, current:
Int, total: Int)')


this modification seems to work :)

WPZipArchive.unzipFileAtPath(help, toDestination: temp, progressHandler: {(entry:String!, info:unz_file_info, current:Int, total:Int) in


}){ (path:String!, succeeded:Bool, error:NSError!) in

}

Answer

I can't see the function name here but there are two handlers (closures) progress handler and the completion handler. I'm not sure which one calls the ((String!, unz_file_info, Int, Int)->Void)!

func foo(completionHandler: (String!, unz_file_info, Int, Int)->Void){
    //do whatever you need to
    completionHandler("this is a string", <object of type unz_file_info>, 1, 2)
}

Alternatively if you are trying use the work with the data from the handler you would implement it

foo(completionHandler: { 
    (w:String!, x:unz_file_info, y:Int, z:Int) in

    print(w)
    print(x)
    print(y)
    print(z)
})

You would put the other parameters first, for more information on closures see: https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html

https://thatthinginswift.com/completion-handlers/

Comments