Swift Coding Standards
Code is written for people to read, and only incidentally for the compiler to understand.
For the same functionality, different people can write completely different Swift code, with huge differences in readability.
This article first covers the core points of Apple's official API Design Guidelines, then moves on to the day-to-day details of naming and formatting, and finally uses an anti-pattern comparison table to explain common bad smells once and for all.
Why Coding Standards Are Needed
Standards are not a matter of aesthetics; they directly affect three things: the speed of reading code, the risk of changing code, and the communication cost of collaboration.
Swift's syntax itself encourages certain styles, such as value types, optional binding, and protocol extensions; following the language's design naturally makes code shorter and clearer.
Most of the conventions below come from Apple's official API Design Guidelines, the same set of standards used when designing Foundation and SwiftUI.
Key Points of the Official API Design Guidelines
The first rule of the guidelines is "clarity at the point of use is more important than brevity", and all the other points can be seen as expansions of this one.
When naming, do not focus on making the definition as short as possible; instead imagine how it reads at the call site.
| Key Points | Description | Example |
|---|---|---|
| Clear at the point of use | Make the call site's intent clear at a glance; prefer longer over ambiguous | articles.filter { !$0.isPublished } |
| Name by role | Name by role rather than type, avoiding words like string and array | greeting rather than string |
| Make parameter labels form sentences | Parameter labels are responsible for making the call site read like an English sentence | move(from:to:) |
| Use -ed / -ing for side-effect-free operations | Methods that return new values end with an adjective, while in-place mutations use a verb | sorted() and sort() |
| Booleans should read like assertions | Boolean properties can be placed directly in an if and read as a sentence | isPublished、hasCover |
| Write contracts in documentation comments | Use - Parameter and - Returns to state inputs, outputs, and preconditions clearly | See the example below |
The following code demonstrates "parameter labels forming sentences" and "writing contracts in documentation comments" together.
Example
import Foundation
struct
RunoobPoint
{
var x
:
Int
var y
:
Int
}
/// Compute the displacement vector from start to end.
/// - Parameters:
/// - start: the starting coordinates.
/// - end: the ending coordinates.
/// - Returns: the new coordinates obtained by subtracting start from end.
func move
(
from start
:
RunoobPoint, to end
:
RunoobPoint
)
RunoobPoint
{
return
RunoobPoint
(
x
:
end.
x
start.
x
, y
:
end.
y
start.
y
)
}
// The call site reads as "move from A to B", with parameter labels carrying the readability
let delta
=
move
(
from
:
RunoobPoint
(
x
:
1
, y
:
1
)
, to
:
RunoobPoint
(
x
:
4
, y
:
5
)
)
(
"Displacement: (delta.x), (delta.y)"
)
extension RunoobPoint
{
// The parameter label by makes the call site read as "scale by factor"
func scaled
(
by factor
:
Int
)
RunoobPoint
{
return
RunoobPoint
(
x
:
x
factor, y
:
y
factor
)
}
}
(
RunoobPoint
(
x
:
2
, y
:
3
)
.
scaled
(
by
:
4
)
)
位移:3, 4
RunoobPoint(x: 8, y: 12)
Note:Since Swift 3, all parameters have only local names by default, and the first parameter is no exception. When an external label is needed, you must explicitly write it func f(label name: Type), and can no longer call it according to Swift 2 rules.
Naming conventions
Naming is the highest-yield item in the standards; the cost of changing a name is extremely low, but it will be read hundreds or thousands of times.
Capitalization and Lexical Conventions
Types, protocols, and enums use UpperCamelCase; properties, methods, parameters, and local variables use lowerCamelCase.
Do not use Hungarian notation by writing the type into the name: forms like strName and iCount are meaningless in Swift, because the type system tells you that.
Use is / has / can prefixes for Boolean properties
Boolean properties should read like an assertion, and placed in an if they become a natural language sentence.
| Prefix | Meaning | Example |
|---|---|---|
| is | Whether a state holds | isPublished、isEmpty |
| has | Whether something is owned | hasCover、hasNext |
| can | Whether a certain capability is possessed | canUndo、canEdit |
| should | Whether something should be done | shouldShowAlert |
Compare: if article.published reads like a noun, while if article.isPublished reads like a judgment.
Avoid Abbreviations
Except for community-recognized abbreviations (such as URL, ID, and JSON), do not invent your own.
viewCount is clearer than vc, and message is clearer than msg; a few extra letters save others from having to guess once.
The following code puts noun naming, Boolean prefixes, and -ed-ending sort methods together.
Example
import Foundation
struct
Article
{
let title
:
String
// Noun: describes the role, not called titleString
var viewCount
:
Int
// Quantity: end with count
var isPublished
:
Bool
// Boolean: is prefix
var hasCover
:
Bool
// Boolean: has prefix
}
let articles
=
[
Article
(
title
:
"Swift Basics"
, viewCount
:
320
, isPublished
:
true
, hasCover
:
true
)
,
Article
(
title
:
"Swift Advanced"
, viewCount
:
180
, isPublished
:
false
, hasCover
:
false
)
,
Article
(
title
:
"Swift Concurrency"
, viewCount
:
520
, isPublished
:
true
, hasCover
:
true
)
]
// Boolean properties can be read directly as conditions, like an English sentence: articles.filter { !$0.isPublished }
let drafts
=
articles.
filter
{
!
$
0
.
isPublished
}
(
drafts.
map
(
.
title
)
)
// Sort methods returning a new array use -ed-ending sorted(by:)
let byViews
=
articles.
sorted
{
$
0
.
viewCount
$
1
.
viewCount
}
(
byViews.
map
(
.
title
)
)
["Swift 进阶"]
["Swift 并发", "Swift 入门", "Swift 进阶"]
Formatting and indentation
Formatting is the least worthwhile thing to argue about; fix it with a tool and no one on the team needs to think about it again.
The Swift toolchain ships with swift format, which can format code or only perform checks.
$ swift format lint RunoobPoint.swift # 检查风格问题,只报错不改文件
$ swift format format RunoobPoint.swift # 把格式化结果写到标准输出
$ swift format format --in-place RunoobPoint.swift # 原地改写文件
If a source file uses 4 spaces for indentation and no space after colons, the check will give a hint like this.
RunoobPoint.swift:1:8: warning: [TypeNamesShouldBeCapitalized] rename the struct 'runoobPoint' using UpperCamelCase; for example, 'RunoobPoint'
RunoobPoint.swift:2:1: warning: [Indentation] unindent by 2 spaces
RunoobPoint.swift:2:11: warning: [Spacing] add 1 space
RunoobPoint.swift:3:1: warning: [Indentation] unindent by 2 spaces
RunoobPoint.swift:3:11: warning: [Spacing] add 1 space
The formatted result is as follows; note that it normalizes indentation to 2 spaces and adds a space after colons.
struct runoobPoint {
var x: Int
var y: Int
}
Note:swift format The default indentation is 2 spaces, while Xcode defaults to 4. Neither is wrong; the key is team consistency. You can place a configuration file in the project root .swift-format to lock it in.
Example
{
"indentation": { "spaces": 4 },
"lineLength": 100
}
The configuration above changes indentation to 4 spaces and sets the maximum line length to 100 characters.
Besides indentation, the following are layout conventions with virtually no controversy in the Swift community.
| Projects | Convention | Example |
|---|---|---|
| Braces | Do not put the opening brace on a new line; else goes on the same line as the closing brace | } else { |
| Colon | Colons hug the variable name with one space after | var x: Int |
| Comma | One space after a comma, none before | f(a, b, c) |
| operator | One space on each side of binary operators | let sum = a + b |
| Semicolon | Do not write a trailing semicolon | Line break instead |
| Import | One module per line, alphabetically sorted | import Foundation |
Idioms
Standards solve "how to write so it doesn't look ugly", while idioms solve "how to write so it looks more like Swift".
The following five are the most frequently seen in everyday code; once mastered, they noticeably reduce the amount of code.
Prefer let
If a value will not change once determined, declare it with let.
This is not fussiness: let lets the compiler catch accidental reassignment for you, and gives the reader one less state to track.
Use guard for early exit
Return immediately when a precondition is not met, keeping the main flow at the outermost level and avoiding layers of nested ifs.
Example
import Foundation
struct
User
{
let name
:
String
let email
:
String
?
let age
:
Int
}
// Not recommended: checks nested layer upon layer, pushing the main flow to the deepest level
func welcomeNested
(
_ user
:
User
)
String
{
if
user.
age
=
18
{
if
let email
=
user.
{
if
!
email.
isEmpty
{
return
"Welcome, (user.name) ((email))"
}
else
{
return
"Email is empty"
}
}
else
{
return
"Email is missing"
}
}
else
{
return
"Minor"
}
}
// Recommended: guard for early exit, keeping the main flow at the outermost level
func welcomeGuard
(
_ user
:
User
)
String
{
guard user.
age
=
18
else
{
return
"Minor"
}
guard let email
=
user.
,
!
email.
isEmpty
else
{
return
"Email is invalid"
}
return
"Welcome, (user.name) ((email))"
}
let runoob
=
User
(
name
:
"Runoob"
:
"dev@runoob.com"
, age
:
20
)
(
welcomeNested
(
runoob
)
)
(
welcomeGuard
(
runoob
)
)
欢迎,Runoob(dev@runoob.com)
欢迎,Runoob(dev@runoob.com)
The two functions produce exactly the same result, but the guard version has no nesting, making exceptional branches visible at a glance.
The same applies in loops: continue when a condition is not met, so the loop body does not need another layer of if.
Example
import Foundation
let raw
=
[
"Runoob"
,
""
,
"www.runoob.com"
,
" "
,
"RUNOOB"
]
// guard is also commonly used in loops: continue when a condition is not met, avoiding a large block nested inside an if
for
name in raw
{
guard
!
name.
trimmingCharacters
(
in
:
.
whitespaces
)
.
isEmpty
else
{
continue
}
(
"Valid entry: (name)"
)
}
有效条目:Runoob
有效条目:www.runoob.com
有效条目:RUNOOB
Use same-name shorthand with if let
When the optional variable name is the same as the constant name to bind, you can omit the = variableName half.
This shorthand is available since Swift 5.7 (SE-0345), and is supported by both if let and guard let.
Example
import Foundation
var siteName
:
String
?
=
"www.runoob.com"
// if let same-name shorthand: no need to write if let siteName = siteName
if
let siteName
{
(
"Site: (siteName)"
)
}
else
{
(
"Site not set"
)
}
// Prefer let: use let when a value will not change again, and the compiler will catch accidental assignments
let welcome
=
"Welcome to (siteName ?? "
RUNOOB
")"
(
welcome
)
// guard let also supports same-name shorthand
func show
(
_ url
:
String
?
)
String
{
guard let url
else
{
return
"No link"
}
return
"Link: (url)"
}
(
show
(
"https://www.runoob.com"
)
)
(
show
(
nil
)
)
站点:www.runoob.com
欢迎访问 www.runoob.com
链接:https://www.runoob.com
无链接
For more on optional types, see 《Swift Optional Types》。
Prefer Value Types
If it can be modeled as a struct or enum, do not use a class.
Value types naturally produce independent copies on assignment and parameter passing, so you do not need to worry about someone secretly changing your data elsewhere.
Example
import Foundation
// Model data with value types: assignment and parameter passing are naturally isolated, with no worry about external changes
struct
RunoobPoint
{
var x
:
Int
var y
:
Int
}
var a
=
RunoobPoint
(
x
:
1
, y
:
2
)
var b
=
a
// Value semantics: b is an independent copy
b.
x
=
100
(
a.
x
, b.
x
)
1 100
When is a class needed? When you need identity, inheritance, or a single mutable state shared in multiple places. For details, see 《Swift Structs》 for the comparison table.
Share Implementations with Protocol Extensions
When multiple types need the same implementation, write the default implementation in a protocol extension instead of copying and pasting into each type.
One change takes effect for all conforming types at once.
Example
import Foundation
// Use a protocol extension to provide default implementations for all conforming types, avoiding repetition in each type
protocol Named
{
var name
:
String
{
get
}
}
extension Named
{
func greeting
(
)
String
{
return
"Hello, (name)"
}
}
struct
Site
:
Named
{
var name
:
String
}
(
Site
(
name
:
"Runoob"
)
.
greeting
(
)
)
(
Site
(
name
:
"www.runoob.com"
)
.
greeting
(
)
)
你好,Runoob
你好,www.runoob.com
Note:Members in a protocol extension do not use dynamic dispatch by default. If a type also implements a method with the same name, calling through the protocol type may still reach the extension's version. This pitfall is explained in detail in 《Swift Protocol Extensions and Protocol-Oriented Programming》.
Anti-pattern comparison table
The following styles all compile, but make code harder to read or more fragile.
Treat them as a quick-reference checklist to consult while writing code.
| Scenario | Not recommended | Recommend | Reason |
|---|---|---|---|
| Mutability | Declaring a value that no longer changes with var | Use let | The compiler helps check, and it also signals intent |
| Prerequisites | Multiple layers of nested ifs | Early exit with guard | Keep the main flow at the outermost level |
| Optional binding | if let x = x { | if let x { | Same-name shorthand is shorter, with identical semantics |
| Data modeling | Using class when struct would work | Prefer struct / enum | Value semantics, avoiding shared mutable state |
| Code Reuse | Copy-pasting into multiple types | Extract into a protocol extension | One change takes effect in multiple places |
| Forced unwrapping | Writing ! everywhere | if let / guard let / ?? | Avoid runtime crashes |
| Naming | let d = 3 | let dayCount = 3 | Names should be readable for their meaning |
| Boolean naming | let published = true | let isPublished = true | Reads like an assertion |
| String concatenation | "Hello, " + name | "Hello, (name)" | Interpolation is clearer and less error-prone |
| Nil fallback | x != nil ? x! : y | x ?? y | Shorter and will not crash |
Common questions
The following questions are most often asked when a team adopts these standards.
Should indentation use 2 or 4 spaces?
Both are widely used; the official tool swift format defaults to 2, while Xcode defaults to 4.
Pick one, write it into a configuration file, and enforce it in CI with swift format lint; then there is no more discussion.
How to choose between guard and if?
Use guard when an unmet condition means you must exit (return, throw, continue, or break).
Use if when the two branches are of equal standing and both continue downward.
Is swift format mandatory?
Not mandatory, but it ships with the toolchain, has zero installation cost, and its rules are configurable.
If the team already uses another formatting tool, just stay consistent; the point is automation, not the tool itself.
Why don't default implementations in protocol extensions take effect?
Because protocol extension members do not use dynamic dispatch, and implementations are chosen at compile time based on the static type.
Putting the method in the protocol requirements themselves, or marking it with @objc to use message dispatch, can change this behavior. For details, see 《Swift Protocol Extensions and Protocol-Oriented Programming》。
Do standards conflict with performance?
Basically no. Most of these conventions only affect readability; for performance, the things to focus on are algorithmic complexity and memory allocation.
When you truly hit a performance bottleneck, measure before optimizing, and do not sacrifice readability for "looking fast".