Group Group Group Group Group Group Group Group Group

Typealias with closure

Hi Team,

Basically this is the code i want to understand why typealias is used

typealias DownloadCountHandler = (Int)->()
var onDownloadFileCompleteCount : DownloadCountHandler?{
didSet{
if onDownloadFileCompleteCount != nil{

        }else{
            
        }
    }
}

i am calling initiallizing this as
if let onDownloadFileCompleteCount = self.onDownloadFileCompleteCount{
self.DownloadCompleteCount(completionHandler: onDownloadFileCompleteCount)
}
this code is fine but when i write the same code as
var onDownloadFileCompleteCount : (Int)->(){
didSet{
if onDownloadFileCompleteCount != nil{

        }else{
            
        }
    }
}

and then i am calling initiallizing this as
if let onDownloadFileCompleteCount = self.onDownloadFileCompleteCount{
self.DownloadCompleteCount(completionHandler: onDownloadFileCompleteCount)
}
and the i am getting error as Initializer for conditional binding must have Optional type, not ‘(Int) -> ()’

Hi @javed,
Typealias is a way to make the code readable, instead of typing (Int) -> () or (Int) -> Void again and again, it is easier and readable as DownloadCountHandler

And the second part of your question,

In the first example you are using

var onDownloadFileCompleteCount : DownloadCountHandler?{

where as in the second example you are using

var onDownloadFileCompleteCount : (Int)->(){

The function is an optional, but you are not declaring it as an optional in your interpretation. You need to use

var onDownloadFileCompleteCount : ((Int)->())? {

then it will all good,
cheers,

A closure can be defined with a typealias . This provides a convenient type placeholder if the same closure signature is used in multiple places. For example, common network request callbacks or user interface event handlers make great candidates for being “named” with a type alias.