Quick error: missing label "name:" in the call

I am studying the default arguments, and I am stranded by something strange:

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

this causes an error:

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

I understand that he wants greet(name: "jiaaro") , but I do not understand why this is necessary.

+9
swift
Jun 04 '14 at 23:29
source share
3 answers

Swift functions can specify the names of local and external arguments:

 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 reject this behavior, you can use the 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") 

Swift 2.0 now disables the following: see equivalent code below.

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") 
+11
Jun 04 '14 at 23:29
source share

Swift requires default tagging, as it supports classes with multiple initializers. The advantage of argument labels comes from Swift's ability to infer which initializer to use; not only by argument type, but also by argument name.

 struct Celsius { var temperatureInCelsius: Double = 0.0 init(fromFahrenheit fahrenheit: Double) { temperatureInCelsius = (fahrenheit - 32.0) / 1.8 } init(fromKelvin kelvin: Double) { temperatureInCelsius = kelvin - 273.15 } } let boilingPointOfWater = Celsius(fromFahrenheit: 212.0) // boilingPointOfWater.temperatureInCelsius is 100.0 let freezingPointOfWater = Celsius(fromKelvin: 273.15) // freezingPointOfWater.temperatureInCelsius is 0.0 

See this page for more details: https://developer.apple.com/library/prerelease/ios/documentation/swift/conceptual/Swift_Programming_Language/Initialization.html#//apple_ref/doc/uid/TP40014097-CH18-XID_272

+3
Jun 07 '14 at 17:24
source share

I just wanted to add that now your code

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

works fine in xcode, I just changed "println" to "print"

+1
Jul 21 '16 at 16:52
source share



All Articles