2015-10-13 110 views
0

我目前正在通过Apple的Swift编程手册工作,并遇到函数类型作为参数类型。函数类型在swift中作为参数类型的优点?

在通常的方式,

func add(one : Int , _ two:Int) ->Int 
{ 
    return one+two 
} 
func multiply(one : Int ,_ two : Int) ->Int 
{ 
    return one*two 
} 
func subtract(one : Int , _ two :Int) ->Int 
{ 
    return one-two 
} 
add(1, 2) 
subtract(1 , 2) 
multiply(1 , 2) 

使用功能类型作为参数,

func add(one : Int , _ two:Int) ->Int 
{ 
    return one+two 
} 
func multiply(one : Int ,_ two : Int) ->Int 
{ 
    return one*two 
} 
func subtract(one : Int , _ two :Int) ->Int 
{ 
    return one-two 
} 

func basic(result : (Int , Int) ->Int,_ one : Int , _ two : Int) 
{ 
    result(one,two) 
} 
basic(add, 1, 2) 
basic(multiply, 2, 3) 

所以,从上面的代码很显然,我们正在编写额外的功能basic()和代码行额外它们是在这个例子中没有用处,并且使它变得复杂。最好不要使用函数类型作为参数类型。

那么,是否有任何利用该功能的例子?

+0

请注意,有关功能的示例不一定非常有用。给一些有用的例子:函数'add'或'multiply'可以存储在字典中。或者你可以提供一个从运算符(例如'+','-')到函数的映射。有一种间接调用函数的方式是一件大事。 – Sulthan

回答

1

如果你看看斯威夫特的标准库,你会看到很多方法可以做到这一点,如map,它在Array上定义。

map采用将数组的元素转换为具有新类型的新数组的函数。

这也是一个通用的功能,但为了保持它的简单我用它映射Int阵列功能:

func map(_ array: [Int], _ transform: Int -> Int) -> [Int] { 
    var result = [Int]() 
    for element in array { 
     result.append(transform(element)) 
    } 
    return result 
} 

// map can be used with other functions 
// and also closures which are functions 
// without a name and can be created "on the fly" 
func addByOne(i: Int) -> Int { 
    return i + 1 
} 
func square(i: Int) -> Int { 
    return i * i 
} 
map([1,2,3], addByOne) // [2,3,4] 
map([1,2,3], square) // [1,4,9] 
// and so on... 

// with closures 
map([1,2,3]) { $0 + 1 } // [2,3,4] 
map([1,2,3]) { $0 * $0 } // [1,4,9] 

所以它主要用于在图书馆,你可以提供具有更广泛的API使用范围。