Search code examples
swiftparametersswift2naming-conventionsfunction-declaration

Why do I need to duplicate the first parameter's label to make it show up in calls?


I have these two functions:

func random() -> CGFloat {
    return CGFloat(Float(arc4random()) / 0xFFFFFFFF)
}
            // here
func random(min min: CGFloat, max: CGFloat) -> CGFloat {
    return random() % (max - min) + min
}

Why I should write min two times in the second function in order to call it like this:

random(min: 1, max: 5);

Solution

  • Remove second min from function. By the way when you call a function, skip the first variable name and just put the value. It's the swift syntax for calling a function

      func random(min: CGFloat, max: CGFloat) -> CGFloat {
          return random() % (max - min) + min
      }
    
      func random() -> CGFloat {
          return CGFloat(Float(arc4random()) / 0xFFFFFFFF)
      }
    
      random(1, max: 5)