Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 417
SLN Avatar asked Jun 19 '16 15:06

SLN


People also ask

What is Typealias in Swift with example?

Type alias in SwiftSwift provides a keyword using which we can refer to primitive data types with an alias or another name. For example, we can refer to Int data type using myInt, Float using myFloat, Double using myDouble. Internally, typealias doesn't create new data types for existing data types.

Whats typealias?

In Swift, typealias is a function that gives a new name, or an alias, to an existing type. This type can be a concrete type, like Double or a custom structure, a compound type, like tuples, or a complex closure type.

What is the use of Typealias?

A type alias allows you to provide a new name for an existing data type into your program. After a type alias is declared, the aliased name can be used instead of the existing type throughout the program. Type alias do not create new types. They simply provide a new name to an existing type.

What is type in Swift?

In Swift, there are two kinds of types: named types and compound types. A named type is a type that can be given a particular name when it's defined. Named types include classes, structures, enumerations, and protocols. For example, instances of a user-defined class named MyClass have the type MyClass .


1 Answers

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
}
like image 167
Code Avatar answered Sep 28 '22 00:09

Code