加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 04:46:22 所属栏目:百科 来源:网络整理
导读:斯威夫特的 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: I
斯威夫特的 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
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读