pkacprzak pkacprzak - 7 months ago 18
Swift Question

Local parameter label naming convention in initializers

Let assume that I have a class like this:

class Foo {

private let userId: String

init(userId givenUserId: String) {
userId = givenUserId
}
}


When I have initializers (or functions) like the above one, so ones setting some internal variable, I like them to have their external parameter name as descriptive as it can be. On the other hand, it is also good to use the same name in the internal class implementation. But then I have to use some local parameter label and the way I do it is by adding a prefix "given" before the external parameter label. Is this a good way to do this or is there any better method or convention to solve the issue?

J2b J2b
Answer

In Swift initializers, you can use the local labels identical to property names. With self. notation, the compiler automatically figures out which one to use for simple assignments. That way, you can have expressive external parameters and avoid the burden of defining both external and internal parameter labels.

class Foo {

    private let userId: String

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