Argument labels and parameter names

Today I learned that something that has been annoying me significantly when working in Swift, has a very simple solution, if only I knew my tools better.

This is a class. I have written a bunch of classes similar to this one:

final class Item {
    private let id: String
    
    init(id: String) {
        self.id = id
    }
}

That self in the constructor, annoys me to no end. I like how self is explicit in Swift, I think it makes the code more readable, less verbose, simpler. So, having it in the constructor, again, annoys me.

The solution is quite simple. Functions can have not only parameter names, but also argument labels.

Each function parameter has both an argument label and a parameter name. The argument label is used when calling the function; each argument is written in the function call with its argument label before it. The parameter name is used in the implementation of the function. By default, parameters use their parameter name as their argument label.

Adding an argument label:

final class BetterItem {
    private let id: String
    
    init(id _id: String) {
        id = _id
    }
}

And client code would remain unchanged:

let item = Item(id: "First")
let betterItem = BetterItem(id: "Better item")

I guess the lesson is, as always, know your tools.

Leave a Reply

Your email address will not be published. Required fields are marked *