2014-06-20 36 views
2

如何編寫一個返回另一個帶有輸入參數的函數的函數?Swift:返回一個輸入輸出函數

我想編寫函數makeIncrementor,它返回一個incrementor函數。這個incrementor函數接受一個I​​n-Out參數並將其增加一定量(它不會返回任何內容)。這裏是我的代碼:

func makeIncrementor(amount:Int) -> Int->Void { 
    func incrementor(inout variable:Int) -> Void { 
     variable += amount; 
    } 
    return incrementor; 
} 

var x = 1; 
var inc = makeIncrementor(2); 
inc(&x) 
//x should now contain 3 

然而,Xcode中提供了以下錯誤:

<REPL>:9:12: error: 'Int' is not a subtype of 'inout Int' 
    return incrementor; 
     ^

我在做什麼錯?

+0

我假設你的意思是'var inc = makeIncrementor(2)'? –

+0

哎呀,是錯別字 – jburns20

回答

0

如果更改返回類型:

func makeIncrementor(amount: Int) -> inout Int -> Void { 
    // ... 
} 

然後錯誤消失,但我的Xcode崩潰。

+0

同樣的事情發生在我身上... – jburns20

+0

我試過了,Xcode崩潰了... –

1

正在返回的函數的參數列表應該包裝在parens中,並且應該在要修改的參數之前包括inout,例如,

(以看得更清楚,在括號包裹的makeIncrementor返回值也一樣)

func makeIncrementor(amount:Int) -> ((inout Int) -> Void) { 
    func incrementor(inout variable:Int) -> Void { 
     variable += amount; 
    } 
    return incrementor; 
} 
+0

現在我收到以下錯誤: 'Playground execution failed:error:error:Could not lookup symbols: __TMdRSi' – jburns20

+0

這可能只是Xcode中的一個錯誤。 – jburns20

1

您返回incrementor功能,它具有類型(inout Int) ->(),而你可以聲明你makeIncrementor功能返回類型Int ->()

這種不匹配是你的錯誤的原因和改變

func makeIncrementor(amount:Int) -> Int->() 

func makeIncrementor(amount : Int) -> (inout Int) ->() 

是正確的修復。但是,如果您目前嘗試在操場上運行該代碼,它將會崩潰!

我已經成功地在OSX和iOS Xcode項目中運行以下代碼,所以在Xcode中操作系統顯然還是存在一些穩定性問題。

func makeIncrementor(amount : Int) -> (inout Int) ->() { 
    func incrementor(inout variable:Int) { 
     variable += amount 
    } 
    return incrementor 
} 

var incByTwo = makeIncrementor(2) 
var incByThree = makeIncrementor(3)  

var a = 5 

println(a) // 5 

incByTwo(&a) 
println(a) // 7 


incByThree(&a) 
println(a) // 10