EndersJeesh
EndersJeesh

Reputation: 457

Variable Naming Convention Thoughts for Swift 3

Concerning Variable Names: Suppose there is some code similar to the following:

class AgentModel
    var name: String?
    var office: String?
    var phone: String?

Would naming-convention dictate that these be named as

class AgentModel
    var nameString: String?
    var officeString: String?
    var phoneString: String?

I haven't been able to find if Apple definitively lays out guidelines for whether one practice is preferred or not, but it doesn't seem Swift-y to always follow the latter, except when necessary.


Concerning Object Names: Similarly, should the object even be named

AgentModel

or should it be named as follows?

Agent

At first glance, I would think that this would follow the same conventions. Am I correct, or would this be an exception to the rule?


Do people have thoughts and/or references for this? Thanks!

Upvotes: 4

Views: 1888

Answers (3)

Jeba Moses
Jeba Moses

Reputation: 849

class AgentModel {
    var name: String?
    var office: String?
    var phone: String?
}

let agent = AgentModel()
agent.name = "EndersJeesh"
agent.office = "London Port"
agent.phone = "180059345345"

This will make life easy. Since the type is already specified in variable declaration "var name: String?" it won't makes sense to add the type in the variable name again.

Upvotes: 0

Martin R
Martin R

Reputation: 539725

The API Design Guidelines on swift.org state (emphasis added):

Omit needless words. Every word in a name should convey salient information at the use site.

More words may be needed to clarify intent or disambiguate meaning, but those that are redundant with information the reader already possesses should be omitted. In particular, omit words that merely repeat type information.

And:

Name variables, parameters, and associated types according to their roles, rather than their type constraints.

So

var nameString: String?
var officeString: String?
var phoneString: String?

is clearly not recommended.

var name: String?
var office: String?
var phone: String?

is good but may be improved further, such as using phoneNumber instead of phone.

Upvotes: 7

Alexander
Alexander

Reputation: 63197

No.

If I needed to know the type and it wasn't obvious from context, I would just option click it and Xcode will give me its declaration, including its access specifier, type and mutability.

Upvotes: 1

Related Questions