2015-01-06 71 views
3

學習Swift並遇到了這個例子。 () - >在第一行中的用途是什麼,以及如何在其他簡單示例中使用它?什麼時候你會在Swift中使用 - >()?

你正在一個功能buildIncrementor,它沒有PARAMATERS和返回功能

->() 

返回一個int:

-> Int 

雖然

func buildIncrementor() ->() -> Int { 
    var count = 0 
    func incrementor() -> Int { 
     ++count 
     return count 
    } 
    return incrementor 
} 

var incrementor = buildIncrementor() 

incrementor() 
incrementor() 

回答

6

這正如讀當我編寫代碼時,我不會寫這個,我喜歡認爲我好像在讀它:

func buildIncrementor() -> (() -> Int) { 
    var count = 0 
    func incrementor() -> Int { 
     ++count 
     return count 
    } 
    return incrementor 
} 

請注意額外的括號。這樣看起來像我所說的:buildIncrementor返回另一個功能。 buildIncrementor返回的函數不帶參數,並返回Int

1

buildIncrementor(),因爲它的返回類型的返回功能。

  • ()指 - 該功能不帶任何參數
  • -> Int意味着它返回一個int,因爲它的返回類型。

總共是類似於:

func buildIncrementor() -> (Void) -> Int 
{ 
} 

或以另一種方式:

func buildIncrementor() -> ((Void) -> Int) 
{ 
} 


incrementor() // Will Return 1 
incrementor() // Will Return 2 

你可以閱讀更多關於返回功能Swift_Programming_Language/Functions

2

buildIncrementor功能需要什麼,並返回一個函數。返回函數的類型是() -> Int,這意味着不需要返回Int。無論何時涉及箭頭,你都在處理函數或閉包。左邊的東西是正確輸出值的輸入值和東西。

4

空的元組()是一樣Void。你可以把它讀作

func buildIncrementor() -> (Void -> Int) 

功能buildIncrementor返回一個類型Void -> Int,這是一個閉合/功能,需要Void(無),並返回Int

BTW功能可以簡化爲

func buildIncrementor() ->() -> Int { 
    var count = 0 
    return { ++count } 
} 
0

您的功能簡潔如下:

func incrementor (var value : Int = 0) ->() -> Int { 
    return { return value++ } 
} 

函數incrementor接受一個參數value並返回() -> Int,它本身就是一個函數。沒有必要命名內部功能incrementor;你可以簡單地使用匿名的「關閉」。您可以使用此作爲

var inc_from_10 = incremenator (value: 10) 
inc_from_10() // 10 
inc_from_10() // 11 

函數返回功能自然在像雨燕一個語言,其中功能是「一流」(分配給變量)。結合泛型類型和一些複雜的形式。

// Return a function to test equality with an obj 
func equate<T> (#pred: (T, T) -> Bool) (x:T) -> (T) -> Bool { 
    return { (y:T) in return pred (x, y) } 
} 

var equalToTen = equate (pred: ==) (x: 10) // curry syntax 

// Return a function to complement a predicate 
func complement<T> (#pred : (T) -> Bool) -> (T) -> Bool { 
    return { (x:T) in return !pred(x) } 
} 

var notEqualToTen = complement(equalToTen) 

// Return a function conjoining two predicates 
func conjoin<T> (#pred1: (T) -> Bool, #pred2: (T) -> Bool) -> (T) -> Bool { 
    return { (x:T) in pred1 (x) && pred2 (x) } 
} 

,現在您開始使用這些,例如,序列功能,如reducemapfilter

相關問題