The casing rule
| Identifier | Convention | Example |
|---|---|---|
| Types (classes, structs, enums) | UpperCamelCase | RadarDetector |
| Protocols | UpperCamelCase | Equatable |
| Everything else, including constants | lowerCamelCase | maxRetryCount |
Because constants fall under "everything else", Swift writes let maxRetryCount = 3, with no CONSTANT_CASE.
Acronyms follow the case of their position
An acronym that's normally written in capitals is uniformly upper- or lower-cased to fit the convention: utf8Bytes at the start of a lowerCamelCase name, isRepresentableAsASCII and userSMTPServer elsewhere. Acronyms that are spoken as words, like radar, are treated as ordinary words: radarDetector.
Naming protocols
A protocol that describes what something is gets a noun: Collection. A protocol that describes a capability ends in able, ible or ing: Equatable, ProgressReporting.
Booleans read as assertions
A nonmutating Boolean method or property should read as a statement about the value: x.isEmpty, line1.intersects(line2).
Mutating and nonmutating pairs
| Kind | Mutating | Nonmutating |
|---|---|---|
| Verb | x.sort() | x.sorted() |
| Verb with an object | stripNewlines() | strippingNewlines() |
| Noun | y.formUnion(z) | y.union(z) |
For a verb, the mutating method is the plain imperative and the nonmutating one takes -ed, or -ing when the verb has a direct object. For a noun, the nonmutating method uses the noun and the mutating one adds form.
Converting names with Transform Case
Our snake_case, camelCase, PascalCase and CONSTANT_CASE converters treat an acronym as one word, so HTTP server error becomes HttpServerError and http_server_error. Swift writes acronyms in all capitals in the middle of a name, so change userSmtpServer to userSMTPServer after converting.
Naming conventions in other languages: Python, Java, C#, Go (Golang), Rust, Kotlin, Dart, PHP. All side by side: 20 languages compared.
Sources
- API Design Guidelines, Swift.org
Questions
Does Swift use CONSTANT_CASE?
No. Only types and protocols are UpperCamelCase; everything else, including constants, is lowerCamelCase.
How are acronyms cased in Swift?
Uniformly: all lowercase at the start of a lowerCamelCase name (utf8Bytes) and all capitals elsewhere (userSMTPServer).
Why sort() and sorted()?
The mutating method uses the imperative verb and the nonmutating one uses the past participle, so sorted() returns a new sorted value.