Reputation: 16758
I tried to define a simple function within viewDidLoad like this:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// my method below
func add(number1:Int, number2:Int)
{
println("sum \(number1 + number2)")
}
add(5, 7) // able to invoke simply by passing values
}
Here I was able to invoke add function simply by passing two integer values, but when I tried to define add method outside viewDidLoad like this:
// my method defined outside viewDidLoad
func add(number1:Int, number2:Int)
{
println("sum \(number1 + number2)")
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
add(5, number2: 7) // for second passed parameter I had to specify name of variable, since compiler was complaining
}
I was unable to invoke it simply by passing the two values, I had to specify name of second variable because compiler was complaining.
Any reasons?
Upvotes: 0
Views: 91
Reputation: 10179
As David pointed out, functions used as methods (functions associated with an object, that is) handle parameters different to "plain" functions to enable ObjC-Style message passing:
Specifically, Swift gives the first parameter name in a method a local parameter name by default, and gives the second and subsequent parameter names both local and external parameter names by default. This convention matches the typical naming and calling convention you will be familiar with from writing Objective-C methods, and makes for expressive method calls without the need to qualify your parameter names.
In other words, Swift treats your function as if you had written it like this if it's defined as method:
func add(number1:Int, #number2:Int)
{
println("sum \(number1 + number2)")
}
Adding the "#" to the second parameter in your first example makes the call work the same in both cases (function and method calling). The "#" itself is a shorthand for a parameter name that matches the local parameter name, so this would work, too:
func add(number1:Int, number2 number2:Int)
{
println("sum \(number1 + number2)")
}
Which makes fixing the interface to make it callable in a more sentence-style way easy (while switching to swift-guide style brace placement):
func add(number1:Int, to number2:Int){
println("sum \(number1 + number2)")
}
someInstance.add(2,to:3)
Update for Swift 3:
With Swift 3.0, this will change and all parameters have to be used when calling the function as declared. See:
https://github.com/apple/swift-evolution/blob/master/proposals/0046-first-label.md
Upvotes: 1
Reputation: 41226
swift handles arguments to methods and functions differently. With methods (for compatibility with Objective-C I suspect) only the initial tag: is omitted, the rest are required. With functions, all of the tags are omitted.
Upvotes: 0