0
class NamedShape {
    var numberOfSides: Int = 0
    var name: String

    init(name: String) {
        self.name = name
    }

    func simpleDescription() -> String {
        return "A shape with \(numberOfSides) sides named \(name)"
    }
}

I have the following example class. To create a new instance, I do

let shape = NamedShape(name: "Test")

The arguments are captured by the init() function, right? However, if I do this:

let shape = NamedShape("Test")

I get a missing argument label error!

However, if I define a silly function like this:

func printInt(numberIn: Int) {
    println(numberIn)
}

I can invoke it just fine using:

printInt(5)

However, if I attempt to invoke it with the arguments formatted in the way I create a class:

printInt(numberIn: 5)

I get an extraneous argument label error!

Help a swift noob understand. Why do I need to label class arguments, but I can't label function arguments? Why are functions and classes different this way? I'm sure there's something I'm missing.

Jaxkr
  • 1,236
  • 2
  • 13
  • 33
  • 1
    possible duplicate of [When are argument labels required in Swift?](http://stackoverflow.com/questions/24815832/when-are-argument-labels-required-in-swift) – jtbandes Dec 02 '14 at 00:02

2 Answers2

1

Because initializer functions aren’t called with a function name, the parameter types and names are used to disambiguate among multiple init() functions. Thus, init() function parameters have external names by default.

You can explicitly opt out of default parameter names with an underscore:

init(_ name: String) {
    self.name = name
}
Jeremy
  • 4,339
  • 2
  • 18
  • 12
0

init() functions are special cases and all parameters are required to have an external name.

https://developer.apple.com/library/ios/documentation/swift/conceptual/Swift_Programming_Language/Initialization.html#//apple_ref/doc/uid/TP40014097-CH18-XID_306

InkGolem
  • 2,662
  • 1
  • 15
  • 22