3e10bf43b7 | ||
---|---|---|
CONTRIBUTING.md | ||
LICENSE | ||
README.md |
README.md
A guide to our Swift style and conventions.
This is an attempt to encourage patterns that accomplish the following goals (in rough priority order):
- Increased rigor, and decreased likelihood of programmer error
- Increased clarity of intent
- Reduced verbosity
- Fewer debates about aesthetics
If you have suggestions, please see our contribution guidelines then open a pull request. ⚡
Prefer implicit getters on read-only properties and subscripts
When possible, omit the get
keyword on read-only computed properties and
read-only subscripts.
So, write these:
var myGreatProperty: Int {
return 4
}
subscript(index: Int) -> T {
return objects[index]
}
… not these:
var myGreatProperty: Int {
get {
return 4
}
}
subscript(index: Int) -> T {
get {
return objects[index]
}
}
Rationale: The intent and meaning of the first version is clear, and results in less code.
Always specify access control explicitly for top-level definitions
Top-level functions, types, and variables should always have explicit access control specifiers:
public var whoopsGlobalState: Int
internal struct TheFez {}
private func doTheThings(things: [Thing]) {}
However, definitions within those can leave access control implicit, where appropriate:
internal struct TheFez {
var owner: Person = Joshaber()
}
Rationale: It's rarely appropriate for top-level definitions to be specifically internal
, and being explicit ensures that careful thought goes into that decision. Within a definition, reusing the same access control specifier is just duplicative, and the default is usually reasonable.
Only explicitly refer to self
when required
When accessing properties or methods on self
, leave the reference to self
implicit by default:
private class History {
var events: [Event]
func rewrite() {
events = []
}
}
Only include the explicit keyword when required by the language—for example, in a closure, or when parameter names conflict:
extension History {
init(events: [Event]) {
self.events = events
}
var whenVictorious: () -> () {
return {
self.rewrite()
}
}
}
Rationale: This makes the capturing semantics of self
stand out more in closures, and avoids verbosity elsewhere.