Swift 3 的变量命名约定思想

Variable Naming Convention Thoughts for Swift 3

关于变量名: 假设有一些类似下面的代码:

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

命名约定是否会规定将这些命名为

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

我没能找到 Apple 是否明确制定了关于是否首选一种做法的指导方针,但似乎 Swift-y 并不总是遵循后者,除非在必要时.


关于对象名称:同样,对象是否应该命名为

AgentModel

还是应该这样命名?

Agent

乍一看,我认为这会遵循相同的约定。我是对的,还是这是规则的例外?


人们对此有想法 and/or 参考吗? 谢谢!

没有

如果我需要知道类型并且从上下文中看不出来,我只需选择单击它,Xcode 会给我它的声明,包括它的访问说明符、类型和可变性。

API Design Guidelines on swift.org 状态(强调已加):

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.

并且:

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

所以

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

显然推荐。

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

很好,但可以进一步改进,例如使用 phoneNumber 而不是 phone.

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

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

这将使生活变得轻松。由于类型已经在变量声明中指定 "var name: String?" 再次在变量名中添加类型是没有意义的。