微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

swift – 如何创建引用特定函数的函数类型的类型

斯威夫特的 official Documents

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 mathFunctionType = (Int,Int) -> Int

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐