Swift: function with default parameter before non-default parameter

后端 未结 4 1011
忘了有多久
忘了有多久 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:37

    If it is a method on a class, you need to call it like this

    class Test
    {
        func f(first:Int = 100, second:Int)
        {
            println("first is \(first)")
            println("second is \(second)")
        }
    
        func other()
        {
            f(second: 4)
            f(first: 30, second: 5)
            //f(4) will not compile, and neither will f(9,12)
        }
    }
    

    If the function f is global, you need to call it like this:

    f(4)
    f(first: 30, 5)
    

    This prints:

    first is 100
    second is 4
    first is 30
    second is 5
    

提交回复
热议问题