official Documents swift 说
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
这里是示例代码:
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
问题:函数类型可以像 Swift 中的任何其他类型一样使用,我想知道,因为我如何创建一个类型别名,它的函数类型采用两个 Int
值,并返回一个 Int
值。设置这个新变量以引用名为 addTwoInts 的函数
我已经试过了,显然,我错了。
最佳答案
您不能将函数分配给 typealias
。
您只能分配一个类型。
typealias mathFunctionType = (Int, Int) -> Int
let mathFunction: mathFunctionType = { int1, int2 in
return int1 + int2
}
关于swift - 如何创建引用特定函数的函数类型的类型别名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37908932/