Jiaaro Jiaaro - 4 months ago 39
Swift Question

Swift error: missing argument label 'name:' in call

I'm learning about default arguments and I ran aground of something weird:

import UIKit

func greet(name: String = "world") {
println("hello \(name)")
}

greet("jiaaro")


this throws an error:


Playground execution failed: error: <REPL>:9:7: error: missing argument label 'name:' in call
greet("jiaaro")
^
name:



I understand that it wants
greet(name: "jiaaro")
but I don't understand why that should be necessary.

Answer

Swift functions can specify local and external argument names:

func greet(who name: String = "world") {
    println("hello \(name)")
}

// prints "hello world"
greet()

// prints "hello jiaaro"
greet(who:"jiaaro")

// error
greet("jiaaro")

// error
greet(name: "jiaaro")

To opt out of this behavior you can use an underscore for the external name. Note that the first parameter implicitly uses the "no external name" behavior:

func greet(name: String = "world", _ hello: String = "hello") {
    println("\(hello) \(name)")
}

// prints "hello world"
greet()

// prints "hello jiaaro"
greet("jiaaro")

// prints "hi jiaaro"
greet("jiaaro", "hi")

// error
greet(name: "jiaaro")

The following is now disallowed in Swift 2.0, see below for equivalent code.

You can use the # prefix to use the same local and external name for the first parameter:

func greet(#name: String = "world", hello: String = "hello") {
    println("\(hello) \(name)")
}

// prints "hi jiaaro"
greet(name: "jiaaro", hello: "hi")

Swift 2.0 code:

func greet(name name: String = "world", hello: String = "hello") {
    println("\(hello) \(name)")
}

// prints "hi jiaaro"
greet(name: "jiaaro", hello: "hi")