When are argument labels required in Swift?

All init methods require parameter names:

var view = NSView(frame: NSRect(x: 10, y: 10, width: 50, height: 50))
class Foo {
    init(one: Int, two: String) { }
}

let foo = Foo(one: 42, two: "Hello world")

All methods called on an object use parameter names for everything but the first parameter:

extension Foo {
    func run(one: String, two: [Int]) { }
}
foo.run("Goodbye", two: [])

All including class functions in Swift and objective-c follow the same pattern. You also can explicitly add external names.

extension Foo{
class func baz(one: Int, two: String){}
class func other(exOne one: Int,  exTwo two: String){}
}
Foo.baz(10, two:"str")
Foo.other(exOne: 20, exTwo:"str")

Swift functions that are not a class function don’t require parameter names, but you still can explicitly add them:

func bar(one: Int, two: String){}
bar(1, "hello")

As Bryan said, it’s to make Swift method calls make sense when called on objective-c methods that have parameter names in the method signature. Init methods include the first parameter because Swift changes the init methods from objective-c from initWith:… to Class() so the first parameter name is no longer included in the method name.

Leave a Comment