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 twoInt
values, and returns anInt
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.
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.
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.
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.
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 .
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With