本帖最后由 cais 于 4-6-2014 22:26 编辑
woodheadz 发表于 4-6-2014 21:38
我的意思就是沿用传统做法,例如这样:回调函数在设计上约等于只拥有一个函数的接口定义。换句话说,当 ...
你的理解是对的。
但是我不赞同 “匿名函数类型” 是不必要的的观点。
就以apple 网站上的例子:https://developer.apple.com/libr ... 014097-CH10-XID_204- func addTwoInts(a: Int, b: Int) -> Int {
- return a + b
- }
- func multiplyTwoInts(a: Int, b: Int) -> Int {
- return a * b
- }
复制代码The type of both of these functions is (Int, Int) -> Int. This can be read as:
“A function type that has two parameters, both of type Int, and that returns a value of type Int.” - var mathFunction: (Int, Int) -> Int = addTwoInts
复制代码This can be read as:
“Define a variable called mathFunction, which has a type of ‘a function that takes two Int values, and returns an Int value.’ Set this new variable to refer to the function called addTwoInts.”
我觉得就是很好的例子。在定义"mathFunction"的时候,的确是没必要再重新给“(Int, Int) -> Int”起个名字,因为只用到一次。
用函数来当另一个函数的参数或返回值也是同样道理。
要起个名字也不是不行,不过这个Swift好像没有提供类似于C的typedef一类的东西。还没看完。目前看到的自定义的type就是class跟struct。好像没有可以像haskell那样可以自由定义新的type的语法。
以上addTwoInts跟multiplyTwoInts其实定义的是实现,是对于"(Int, Int) -> Int“这个函数类型的实现,并不是定义了函数类型本身。
你说的以下用法是有问题的。- var sayHello : SayHelloCallback;
复制代码 假设swift可以自动推导类型的话,最多也只是写成- var sayHello = SayHelloCallback;
复制代码 此外匿名函数对于closure的用处也很大:https://developer.apple.com/libr ... 014097-CH11-XID_117 |