STOP PRESS: Updated for Swift 2.0 here!
How function parameters work in Swift can be a little confusing, here’s an attempt to make it clearer:
1. func
By default parameters of funcs do not have external names:
func test(a:String,b:String, c:String) { (a,b,c) } test("A", "B", "C")
If you want to force your func to have external names, you can put a hash symbol before each parameter:
func test(#a:String,#b:String,#c:String) { (a,b,c) } test(a: "A", b: "B",c:"C")
Alternatively, if you would like your func to have external parameter names that are distinct from internal parameter names, you can explicitly declare them:
func test(a internalA:String, b internalB:String, c internalC:String) { (internalA,internalB,internalC) } test(a: "A", b: "B", c: "C")
2. class methods
Class methods work differently by default. Similar to Objective C, the first parameter has no external parameter name, but following parameters have external names by default:
class Box { func test(a:String,b:String,c:String) { (a,b,c) } } var box=Box() box.test("A", b: "B", c: "C")
Similar to funcs outside of a class, you can require an external name for the first parameter as well with a hash symbol(or explicitly giving it an external parameter name):
class Box { func test(#a:String,b:String,c:String) { (a,b,c) } } var box=Box() box.test(a:"A", b: "B", c: "C")
If you would rather the method not require external parameter names, you can achieve this by using the underscore(_): (this is only necessary from the second parameter)
class Box { func test(a:String,_ b:String,_ c:String) { (a,b,c) } } var box=Box() box.test("A", "B","C")
3. class init methods
Init methods work differently again by default. Init methods require ALL parameter names:
class Box { init(a:String,b:String,c:String) { (a,b,c) } } var box=Box(a: "A",b:"B",c:"C")
Similar to class methods, if you would prefer the parameter names to be implicit, you can use underscores(_) to achieve this:
class Box { init(_ a:String,_ b:String,_ c:String) { (a,b,c) } } var box=Box("A","B","C")
For more on func parameters, I look into optional parameters here.
[…] For info just on function parameters in Swift, click on my post here. […]