SLN SLN - 5 months ago 7
Swift Question

How to create typealias of a function type which refers to a particular function

The official Documents of Swift says


You use function types just like any other types in Swift. For example, you can define a constant or variable to be of a function type and assign an appropriate function to that variable:


func addTwoInts(a: Int, _ b: Int) -> Int {
return a + b
}

var mathFunction: (Int, Int) -> Int = addTwoInts


Here inside the sample code:


it Define a variable called
mathFunction
, which has a type of a function that takes two
Int
values, and returns an
Int
values. Set this new variable to refer to the function called addTwoInts


Question: The function type can be used like any other types in Swift, I wonder, since how can I create a type alias which has a type of a function that takes two
Int
values, and returns an
Int
values. Set this new variable to refer to the function called addTwoInts

I've tried this, obviously, I was wrong.

enter image description here

Answer

You cannot assign a function to a typealias.

You can only assign a type.

typealias mathFunctionType = (Int, Int) -> Int

let mathFunction: mathFunctionType = { int1, int2 in
    return int1 + int2
}
Comments