tonytran tonytran - 5 months ago 9
iOS Question

define a closure and execute it later on, swift

I am defining a block which takes 2

String
and return nothing

var editingAssignmentBlock : ((String, String) -> Void)?


And I successfully execute block by doing this

guard let block = self.editingAssignmentBlock else
{
return
}
block("This is a new shift", "This is a new type")
}


Alternative, If I define a block using
typealias
like following

typealias editingAssignmentBlock = ((String, String) -> Void)?


If I am using the same way to execute a block like I did and I am getting an error like below

initializer for conditional binding must have Optional type, not 'editingAssignmentBlock.Type'(aka 'Optional<(String,String) -> ()>.Type')


Can anyone know what I am doing wrong when using
typealias
to define a block.

Answer

There's no problem here. You didn't show your real code, so who knows what's wrong with it? But I did this, and it compiles just fine:

typealias MyEditingAssignmentBlock = ((String, String) -> Void)?
var editingAssignmentBlock : MyEditingAssignmentBlock
func test() {
    guard let block = self.editingAssignmentBlock else {return}
    block("hey", "ho")
}

EDIT I think the problem is that you don't understand what a type alias is. It merely gives a name to a type. It defines a synonym. It doesn't do anything else for you. If you want a variable editingAssignmentBlock, you still need to declare it as a variable (as in my code).

In other words, think of a type alias as a form of text substitution. When you say

typealias MyEditingAssignmentBlock = ((String, String) -> Void)?

you are saying: "Whenever I write MyEditingAssignmentBlock, substitute ((String, String) -> Void)?". So when I say:

typealias MyEditingAssignmentBlock = ((String, String) -> Void)?
var editingAssignmentBlock : MyEditingAssignmentBlock

...that is the same as performing that substitution and saying:

var editingAssignmentBlock : ((String, String) -> Void)?

But the type alias itself does not declare the var for you, by some kind of magic voodoo. The var declaration is still just a var declaration and you still need to make it explicitly if that's what you want.

Similarly, when Apple says typealias TimeInterval = Double, that just means "From now on, TimeInterval is another word for Double." It doesn't cause any variables to pop magically into existence.