swift - 如何创建引用特定函数的函数类型的类型别名

标签 swift function types

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 two Int values, and returns an Int values. Set this new variable to refer to the function called addTwoInts

问题:函数类型可以像 Swift 中的任何其他类型一样使用,我想知道,因为我如何创建一个类型别名,它的函数类型采用两个 Int 值,并返回一个 Int 值。设置这个新变量以引用名为 addTwoInts 的函数

我已经试过了,显然,我错了。

enter image description here

最佳答案

您不能将函数分配给 typealias

您只能分配一个类型。

typealias mathFunctionType = (Int, Int) -> Int

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

关于swift - 如何创建引用特定函数的函数类型的类型别名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37908932/

相关文章:

swift - 如何通过更改单元格的高度来创建动态 TableView 页脚

javascript - 将 jquery 选择器作为参数传递

java - 在Java中,我如何在函数 "1"(不使用参数)中使用在函数 "A"内部生成的数组 "B"?

ios - 将谓词应用于数组中的元素

ios - Swift Alamofire 从刷新 token 请求错误中获取 token

ios - Swift 将 NSTimeInteval 转换为 NSDate

python - 带有类中函数字典的 self 参数

scala - 案例类字段中的递归类型参数

vb.net - 是否可以在 VB.net 中测试两种类型是否具有相同的未知继承?

java - 在 Java 中确定 'type'