簡體   English   中英

如何在Swift中使用inout參數和Void的返回類型返回函數?

[英]How do I return functions with inout parameters and a return type of Void in Swift?

我試圖通過viewController viewDidLoad函數在Xcode 6.0游樂場和iOS項目中運行此代碼,在這兩種設置下,程序都會使編譯器崩潰。 我讀過一些關於人們在程序在操場上運行時返回inout函數時遇到類似問題的信息,但是當他們在項目中運行程序時,這個問題就解決了。 我的代碼有問題嗎?如果是,那是什么問題?或者我在操場或項目中錯誤地運行了代碼?

// testingPlayground
// July 18, 2015


func chooseFunction(isYNegative lessThanZero: Bool) -> (inout Int) -> Void {
    func increaseY(inout #yValue: Int){ // Increases yValue
        yValue += 1
    }

    func decreaseY(inout #yValue: Int){ // Decreases yValue
        yValue -= 1
    }

    return lessThanZero ? increaseY : decreaseY // Returns either the increase or decrease yValue function
}


var yValue = -1
var changeYFunction = chooseFunction(isYNegative: yValue < 0)


while yValue != 0 {
    changeYFunction(&yValue) // Increments/Decrements yValue
}

該代碼工作正常,我取出后#從雙方的#yValue: Int參數內chooseFunction (具有#將意味着一個參數名稱必須給,你不這樣做)。

另外,您需要在chooseFunction的返回類型中指定參數名稱,並在調用返回的函數時使用它,即:

func chooseFunction(isYNegative lessThanZero: Bool) -> ((inout yValue: Int) -> Void) {

和:

changeYFunction(yValue: &yValue)

換句話說,問題在於您與返回的函數是否要求參數名稱不一致。

編輯 :作為另一種選擇,您可以考慮重構整個事物,例如,使用簡寫為咖喱函數:

func stepper(increase increase: Bool)(inout _ y: Int) {
    increase ? ++y : --y
}
var y = -5
let step = stepper(increase: y < 0)
while y != 0 {
    step(&y)
}

實際上,即使以下工作也可以實現,盡管所需的冗長語法使我警惕:

func stepper(increase increase: Bool)(inout _ y: Int)() {
    increase ? ++y : --y
}
var y = -5
let stepY = stepper(increase: y < 0)(&y)
while y != 0 {
    stepY()
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM