What this line means in Swift?

前端 未结 3 1982
别跟我提以往
别跟我提以往 2021-01-24 11:10

I\'m now reading Swift 3 book and found this line there:

func sumOf(numbers: Int...) -> Int {

}

and there are just this description:

<
相关标签:
3条回答
  • 2021-01-24 11:33

    Example for using function with varidic arguments

    func log(args: AnyObject ...) {
      var text = ""
      for arg in args {
        text += " \(arg)"
      }
      print("\(text)")
    }
    

    log("Arg1", "Arg2")

    log("Arg1", "Arg2", "Arg3")

    0 讨论(0)
  • 2021-01-24 11:48

    As per the above explanation the variadic arguments are variable number of argument the function takes variable number of arguments in a numbers array. so if you want to print each element you can do so by

    func sumOf(numbers: Int...) -> Int {
        var sum:Int = 0
    
        for num in numbers {
            sum = sum + num
        }
        return sum
    }
    

    and the number of int element passed to this number may very.

    0 讨论(0)
  • 2021-01-24 11:53

    It's called variadic arguments, explained here.

    A variadic parameter accepts zero or more values of a specified type. You use a variadic parameter to specify that the parameter can be passed a varying number of input values when the function is called. Write variadic parameters by inserting three period characters (...) after the parameter’s type name.

    0 讨论(0)
提交回复
热议问题