如何使用默认值使闭包可选

时间:2015-02-13 21:18:16

标签: ios swift

我有一堆函数,如果没有提供,我希望能够指定一个默认的闭包。如果没有一些丑陋的代码,我似乎无法弄清楚如何做到这一点。

因此,例如,我希望perform函数接受一个名为closure的可选参数,该参数在提供时执行。否则,它将默认执行myClosure。我怎样才能做得更好,所以我不必重复函数调用?

class MyClas {

    typealias closureType = ((number: Int) -> Int)?

    func myClosure (number: Int) -> Int {
        return number * 2
    }

    func perform(number: Int, closure: closureType = nil) -> Int {
        if closure == nil {
            return myClosure(number)
        } else {
            return closure!(number: number)
        }

    }
}

理想情况下,我可以做到这一点!

class MyClass {

    typealias closureType = ((number: Int) -> Int)?

    func myClosure (number: Int) -> Int {
        return number * 2
    }

    func perform(number: Int, closure: closureType = myClosure) -> Int {
        return closure(number: number)

    }
}

2 个答案:

答案 0 :(得分:3)

您的问题是您已经制作了myClosure方法(或会员功能),这意味着它没有您想要的签名(而不是咖喱功能) ,类型MyClass->Int->Int)。

要么将它拉出课堂,要么使它成为静态(或者更确切地说是#34;类"在类的情况下)方法:

class MyClass {

    typealias closureType = (number: Int) -> Int

    class func myClosure (number: Int) -> Int {
        return number * 2
    }

    func perform(number: Int, closure: closureType = MyClass.myClosure) -> Int {
        return closure(number: number)

    }
}

P.S。一旦你这样做,它就不再需要是可选的了

只是为了表明它是一种非静态方法:

class MyClass {

    typealias closureType = MyClass -> (number: Int) -> Int

    func myClosure (number: Int) -> Int {
        return number * 2
    }

    func perform(number: Int, closure: closureType = myClosure) -> Int {
        return closure(self)(number: number)

    }
}

let c = MyClass()
println(c.perform(5))  // prints 10

答案 1 :(得分:1)

Closure是 Swift 中的一等公民。所以你可以为它提供默认值。

class MyClass {
    func perform(number: Int, closure: Int -> Int = { $0 * 2 }) -> Int {
        return closure(number)
    }
}