Swift: function with default parameter before non-default parameter

后端 未结 4 1009
忘了有多久
忘了有多久 2021-02-01 13:01

say I have a function that has non-default parameter after default parameter like this:

func f(first:Int = 100, second:Int){}

how can I call it

4条回答
  •  生来不讨喜
    2021-02-01 13:43

    On Swift 3:

    func defaultParameterBefore(_ x: Int = 1, y: Int ) {}
    

    Calling

    defaultParameterBefore(2)
    

    will raise this error

    error: missing argument for parameter 'y' in call
    

    The only exception is:

    • There is a parameter before the default parameter;
    • and the parameter after the default parameter is a closure;
    • and the closure parameter is the last parametr;
    • and calling via trailing closure

    For example:

    func defaultParameterBetween(_ x: Int, _ y: Bool = true, _ z: String) {
        if y {
           print(x)
        } else
           z()
        }
    }
    
    // error: missing argument for parameter #3 in call
    // defaultParameterWithTrailingClosure(1, { print(0) }
    
    // Trailing closure does work, though.
    func defaultParameterWithTrailingClosure(_ x: Int, y: Bool = true,
                                         _ z: () -> Void) {
        if y {
            print(x)
        } else {
            z()
        }
    }
    
    defaultParameterWithTrailingClosure(1) { print(0) }
    

    swift version: DEVELOPMENT-SNAPSHOT-2016-04-12

提交回复
热议问题