func parameters in Swift

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.

Interactive developer, Author - iOS development with Swift - book coming 2017 https://manning.com/books/ios-development-with-swift

Tagged with:
Posted in Swift
One comment on “func parameters in Swift
  1. […] For info just on function parameters in Swift, click on my post here. […]

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: