Do you need help on a specific subject? Use the contact form (Request a blog entry) on the right hand side.

2015-01-27

Variadics

Variadics are a neat trick to pass an unknown number of parameters of a single type to a function.
While you could use arrays or dictionaries to do the same, it looks better if you can do it as a variadic parameter.

A variadic parameter is specified as follows:

    func objectAtPath(path: String...) -> MyDataClass? {...}

Unfortunately it cannot be used for multiple types. For that you will need to use an Array or a Dictionary.

Inside the function it is used as if the variadic parameter was an array:

    if path.count == 0 { return nil }

    let name = path[0]

It is not possible to pass the parameter through to functions that are called from with the function that takes it as a parameter, specifically the following is NOT possible:

    if path.count == 0 { return nil }

    let name = path[0]
    
    return objectAtPath(path[1..<path.count])

Which is a pity as functions with a variadic parameter will often be perfect candidates for recursive calls.

Maybe Apple will add this kind of functionality in future version, but for now we need to work around this. It can be done by creating one version of the function that takes an array and one that uses the variadic parameter. The one with the variadic can then call the one with the array, like this:

    func objectAtPath(path: Array<String>) -> MyDataClass? {...}

    func objectAtPath(path: String...) -> MyDataClass? { return objectAtPath(path) }

You can then choose whether to use:

    let name = objectAtPath(["root""level1", "level2"])

Or the slightly better looking:

    let name = objectAtPath("root""level1", "level2")

Happy coding...

Did this help?, then please help out a small independent.
If you decide that you want to make a small donation, you can do so by clicking this
link: a cup of coffee ($2) or use the popup on the right hand side for different amounts.
Payments will be processed by PayPal, receiver will be sales at balancingrock dot nl
Bitcoins will be gladly accepted at: 1GacSREBxPy1yskLMc9de2nofNv2SNdwqH

We don't get the world we wish for... we get the world we pay for.

No comments:

Post a Comment