- andOperator
- anyObjectProtocol
- blankLinesAroundMark
- blankLinesAtEndOfScope
- blankLinesAtStartOfScope
- blankLinesBetweenScopes
- braces
- consecutiveBlankLines
- consecutiveSpaces
- duplicateImports
- elseOnSameLine
- emptyBraces
- fileHeader
- hoistPatternLet
- indent
- isEmpty
- leadingDelimiters
- linebreakAtEndOfFile
- linebreaks
- numberFormatting
- ranges (deprecated)
- redundantBackticks
- redundantBreak
- redundantExtensionACL
- redundantFileprivate
- redundantGet
- redundantInit
- redundantLet
- redundantLetError
- redundantNilInit
- redundantObjc
- redundantParens
- redundantPattern
- redundantRawValues
- redundantReturn
- redundantSelf
- redundantVoidReturnType
- semicolons
- sortedImports
- spaceAroundBraces
- spaceAroundBrackets
- spaceAroundComments
- spaceAroundGenerics
- spaceAroundOperators
- spaceAroundParens
- spaceInsideBraces
- spaceInsideBrackets
- spaceInsideComments
- spaceInsideGenerics
- spaceInsideParens
- specifiers
- strongOutlets
- strongifiedSelf
- todos
- trailingClosures
- trailingCommas
- trailingSpace
- typeSugar
- unusedArguments
- void
- wrap
- wrapArguments
- yodaConditions
Prefer comma over && in if, guard or while conditions.
Examples
- if true && true {
+ if true, true {- guard true && true else {
+ guard true, true else {- if functionReturnsBool() && true {
+ if functionReturnsBool(), true {- if functionReturnsBool() && variable {
+ if functionReturnsBool(), variable {Prefer AnyObject over class in protocol definitions.
Examples
- protocol Foo: class {}
+ protocol Foo: AnyObject {}NOTE: The guideline to use AnyObject instead of class was only
introduced in Swift 4.1, so the anyObjectProtocol rule is disabled unless the
swift version is set to 4.1 or above.
Insert blank line before and after MARK: comments.
Examples
func foo() {
// foo
}
// MARK: bar
func bar() {
// bar
}
func foo() {
// foo
}
+
// MARK: bar
+
func bar() {
// bar
}Remove trailing blank line at the end of a scope.
Examples
func foo() {
// foo
-
}
func foo() {
// foo
} array = [
foo,
bar,
baz,
-
]
array = [
foo,
bar,
baz,
]Remove leading blank line at the start of a scope.
Examples
func foo() {
-
// foo
}
func foo() {
// foo
} array = [
-
foo,
bar,
baz,
]
array = [
foo,
bar,
baz,
]Insert blank line before class, struct, enum, extension, protocol or function declarations.
Examples
func foo() {
// foo
}
func bar() {
// bar
}
var baz: Bool
var quux: Int
func foo() {
// foo
}
+
func bar() {
// bar
}
+
var baz: Bool
var quux: IntWrap braces in accordance with selected style (K&R or Allman).
| Option | Description |
|---|---|
--allman |
Use allman indentation style: "true" or "false" (default) |
Examples
- if x
- {
// foo
}
- else
- {
// bar
}
+ if x {
// foo
}
+ else {
// bar
}Replace consecutive blank lines with a single blank line.
Examples
func foo() {
let x = "bar"
-
print(x)
}
func foo() {
let x = "bar"
print(x)
}Replace consecutive spaces with a single space.
Examples
- let foo = 5
+ let foo = 5Remove duplicate import statements.
Examples
import Foo
import Bar
- import Foo import B
#if os(iOS)
import A
- import B
#endifPlace else, catch or while keyword in accordance with current style (same or
next line).
| Option | Description |
|---|---|
--elseposition |
Placement of else/catch: "same-line" (default) or "next-line" |
Examples
if x {
// foo
- }
- else {
// bar
}
if x {
// foo
+ } else {
// bar
} do {
// try foo
- }
- catch {
// bar
}
do {
// try foo
+ } catch {
// bar
} repeat {
// foo
- }
- while {
// bar
}
repeat {
// foo
+ } while {
// bar
}Remove whitespace inside empty braces.
Examples
- func foo() {
-
- }
+ func foo() {}Use specified source file header template for all files.
| Option | Description |
|---|---|
--header |
Header comments: "strip", "ignore", or the text you wish use |
Reposition let or var bindings within pattern.
| Option | Description |
|---|---|
--patternlet |
let/var placement in patterns: "hoist" (default) or "inline" |
Examples
- (let foo, let bar) = baz()
+ let (foo, bar) = baz()- if case .foo(let bar, let baz) = quux {
// inner foo
}
+ if case let .foo(bar, baz) = quux {
// inner foo
}Indent code in accordance with the scope level.
| Option | Description |
|---|---|
--indent |
Number of spaces to indent, or "tab" to use tabs |
--tabwidth |
The width of a tab character. Defaults to "unspecified" |
--indentcase |
Indent cases inside a switch: "true" or "false" (default) |
--ifdef |
#if indenting: "indent" (default), "no-indent" or "outdent" |
--xcodeindentation |
Xcode indent guard/enum: "enabled" or "disabled" (default) |
Examples
if x {
- // foo
} else {
- // bar
- }
if x {
+ // foo
} else {
+ // bar
+ } let array = [
foo,
- bar,
- baz
- ]
let array = [
foo,
+ bar,
+ baz
+ ] switch foo {
- case bar: break
- case baz: break
}
switch foo {
+ case bar: break
+ case baz: break
}Prefer isEmpty over comparing count against zero.
Examples
- if foo.count == 0 {
+ if foo.isEmpty {
- if foo.count > 0 {
+ if !foo.isEmpty {
- if foo?.count == 0 {
+ if foo?.isEmpty == true {NOTE: In rare cases, the isEmpty rule may insert an isEmpty call for
a type that doesn't implement that property, breaking the program. For this
reason, the rule is disabled by default, and must be manually enabled via the
--enable isEmpty option.
Move leading delimiters to the end of the previous line.
Examples
- guard let foo = maybeFoo // first
- , let bar = maybeBar else { ... }
+ guard let foo = maybeFoo, // first
+ let bar = maybeBar else { ... }Add empty blank line at end of file.
Use specified linebreak character for all linebreaks (CR, LF or CRLF).
| Option | Description |
|---|---|
--linebreaks |
Linebreak character to use: "cr", "crlf" or "lf" (default) |
Use consistent grouping for numeric literals.
| Option | Description |
|---|---|
--decimalgrouping |
Decimal grouping,threshold (default: 3,6) or "none", "ignore" |
--binarygrouping |
Binary grouping,threshold (default: 4,8) or "none", "ignore" |
--octalgrouping |
Octal grouping,threshold (default: 4,8) or "none", "ignore" |
--hexgrouping |
Hex grouping,threshold (default: 4,8) or "none", "ignore" |
--fractiongrouping |
Group digits after '.': "enabled" or "disabled" (default) |
--exponentgrouping |
Group exponent digits: "enabled" or "disabled" (default) |
--hexliteralcase |
Casing for hex literals: "uppercase" (default) or "lowercase" |
--exponentcase |
Case of 'e' in numbers: "lowercase" or "uppercase" (default) |
Examples
- let color = 0xFF77A5
+ let color = 0xff77a5- let big = 123456.123
+ let big = 123_456.123Add or remove space around range operators.
Note: ranges rule is deprecated. Use spaceAroundOperators instead.
Remove redundant backticks around identifiers.
Examples
- let `infix` = bar
+ let infix = bar- func foo(with `default`: Int) {}
+ func foo(with default: Int) {}Remove redundant break in switch case.
Examples
switch foo {
case bar:
print("bar")
- break
default:
print("default")
- break
}Remove redundant access control specifiers.
Examples
public extension URL {
- public func queryParameter(_ name: String) -> String { ... }
}
public extension URL {
+ func queryParameter(_ name: String) -> String { ... }
}Prefer private over fileprivate where equivalent.
Examples
- fileprivate let someConstant = "someConstant"
+ private let someConstant = "someConstant"In Swift 4 and above, fileprivate can also be replaced with private for
members that are only accessed from extensions in the same file:
class Foo {
- fileprivate var foo = "foo"
+ private var foo = "foo"
}
extension Foo {
func bar() {
print(self.foo)
}
}Remove unneeded get clause inside computed properties.
Examples
var foo: Int {
- get {
- return 5
- }
}
var foo: Int {
+ return 5
}Remove explicit init if not required.
Examples
- String.init("text")
+ String("text")Remove redundant let/var from ignored variables.
Examples
- let _ = foo()
+ _ = foo()Remove redundant let error from catch clause.
Examples
- do { ... } catch let error { log(error) }
+ do { ... } catch { log(error) }Remove redundant nil default value (Optional vars are nil by default).
Examples
- var foo: Int? = nil
+ var foo: Int?// doesn't apply to `let` properties
let foo: Int? = nil// doesn't affect non-nil initialization
var foo: Int? = 0Remove redundant @objc annotations.
Examples
- @objc @IBOutlet var label: UILabel!
+ @IBOutlet var label: UILabel!- @IBAction @objc func goBack() {}
+ @IBAction func goBack() {}- @objc @NSManaged private var foo: String?
+ @NSManaged private var foo: String?Remove redundant parentheses.
Examples
- if (foo == true) {}
+ if foo == true {}- while (i < bar.count) {}
+ while i < bar.count {}- queue.async() { ... }
+ queue.async { ... }- let foo: Int = ({ ... })()
+ let foo: Int = { ... }()Remove redundant pattern matching parameter syntax.
Examples
- if case .foo(_, _) = bar {}
+ if case .foo = bar {}- let (_, _) = bar
+ let _ = barRemove redundant raw string values for enum cases.
Examples
enum Foo: String {
- case bar = "bar"
case baz = "quux"
}
enum Foo: String {
+ case bar
case baz = "quux"
}Remove unneeded return keyword.
Examples
- array.filter { return $0.foo == bar }
+ array.filter { $0.foo == bar }Insert/remove explicit self where applicable.
| Option | Description |
|---|---|
--self |
Explicit self: "insert", "remove" (default) or "init-only" |
--selfrequired |
Comma-delimited list of functions with @autoclosure arguments |
Examples
func foobar(foo: Int, bar: Int) {
self.foo = foo
self.bar = bar
- self.baz = 42
}
func foobar(foo: Int, bar: Int) {
self.foo = foo
self.bar = bar
+ baz = 42
}In the rare case of functions with @autoclosure arguments, self may be
required at the call site, but SwiftFormat is unable to detect this
automatically. You can use the --selfrequired command-line option to specify
a list of such methods, and the redundantSelf rule will then ignore them.
An example of such a method is the expect() function in the Nimble unit
testing framework (https://github.com/Quick/Nimble), which is common enough that
SwiftFormat excludes it by default.
There is also an option to always use explicit self but only inside init,
by using --self init-only:
init(foo: Int, bar: Int) {
self.foo = foo
self.bar = bar
- baz = 42
}
init(foo: Int, bar: Int) {
self.foo = foo
self.bar = bar
+ self.baz = 42
}Remove explicit Void return type.
Examples
- func foo() -> Void {
// returns nothing
}
+ func foo() {
// returns nothing
}Remove semicolons.
| Option | Description |
|---|---|
--semicolons |
Allow semicolons: "never" or "inline" (default) |
Examples
- let foo = 5;
+ let foo = 5- let foo = 5; let bar = 6
+ let foo = 5
+ let bar = 6// semicolon is not removed if it would affect the behavior of the code
return;
goto(fail)Sort import statements alphabetically.
| Option | Description |
|---|---|
--importgrouping |
"testable-top", "testable-bottom" or "alphabetized" (default) |
Examples
- import Foo
- import Bar
+ import Bar
+ import Foo- import B
- import A
- #if os(iOS)
- import Foo-iOS
- import Bar-iOS
- #endif
+ import A
+ import B
+ #if os(iOS)
+ import Bar-iOS
+ import Foo-iOS
+ #endifAdd or remove space around curly braces.
Examples
- foo.filter{ return true }.map{ $0 }
+ foo.filter { return true }.map { $0 }- foo( {} )
+ foo({})Add or remove space around square brackets.
Examples
- foo as[String]
+ foo as [String]- foo = bar [5]
+ foo = bar[5]Add space before and/or after comments.
Examples
- let a = 5// assignment
+ let a = 5 // assignment- func foo() {/* ... */}
+ func foo() { /* ... */ }Remove space around angle brackets.
Examples
- Foo <Bar> ()
+ Foo<Bar>()Add or remove space around operators or delimiters.
| Option | Description |
|---|---|
--operatorfunc |
Spacing for operator funcs: "spaced" (default) or "no-space" |
--nospaceoperators |
Comma-delimited list of operators without surrounding space |
Examples
- foo . bar()
+ foo.bar()- a+b+c
+ a + b + c- func ==(lhs: Int, rhs: Int) -> Bool
+ func == (lhs: Int, rhs: Int) -> BoolAdd or remove space around parentheses.
Examples
- init (foo)
+ init(foo)- switch(x){
+ switch (x) {Add or remove space inside curly braces.
Examples
- foo.filter {return true}
+ foo.filter { return true }Remove space inside square brackets.
Examples
- [ 1, 2, 3 ]
+ [1, 2, 3]Add leading and/or trailing space inside comments.
Examples
- let a = 5 //assignment
+ let a = 5 // assignment- func foo() { /*...*/ }
+ func foo() { /* ... */ }Remove space inside angle brackets.
Examples
- Foo< Bar, Baz >
+ Foo<Bar, Baz>Remove space inside parentheses.
Examples
- ( a, b)
+ (a, b)Use consistent ordering for member specifiers.
| Option | Description |
|---|---|
--specifierorder |
Comma-delimited list of specifiers in preferred order |
Examples
- lazy public weak private(set) var foo: UIView?
+ public private(set) lazy weak var foo: UIView?- final public override func foo()
+ override public final func foo()- convenience private init()
+ private convenience init()Remove weak specifier from @IBOutlet properties.
Examples
As per Apple's recommendation (https://developer.apple.com/videos/play/wwdc2015/407/ @ 32:30).
- @IBOutlet weak var label: UILabel!
+ @IBOutlet var label: UILabel!Remove backticks around self in Optional unwrap expressions.
Examples
- guard let `self` = self else { return }
+ guard let self = self else { return }NOTE: assignment to un-escaped self is only supported in Swift 4.2 and
above, so the strongifiedSelf rule is disabled unless the swift version is
set to 4.2 or above.
Use correct formatting for TODO:, MARK: or FIXME: comments.
Examples
- /* TODO fix this properly */
+ /* TODO: fix this properly */- // MARK - UIScrollViewDelegate
+ // MARK: - UIScrollViewDelegateUse trailing closure syntax where applicable.
| Option | Description |
|---|---|
--trailingclosures |
Comma-delimited list of functions that use trailing closures |
Examples
- DispatchQueue.main.async(execute: { ... })
+ DispatchQueue.main.async {- let foo = bar.map({ ... }).joined()
+ let foo = bar.map { ... }.joined()Add or remove trailing comma from the last item in a collection literal.
| Option | Description |
|---|---|
--commas |
Commas in collection literals: "always" (default) or "inline" |
Examples
let array = [
foo,
bar,
- baz
]
let array = [
foo,
bar,
+ baz,
]Remove trailing space at end of a line.
| Option | Description |
|---|---|
--trimwhitespace |
Trim trailing space: "always" (default) or "nonblank-lines" |
Prefer shorthand syntax for Arrays, Dictionaries and Optionals.
Examples
- var foo: Array<String>
+ var foo: [String]- var foo: Dictionary<String, Int>
+ var foo: [String: Int]- var foo: Optional<(Int) -> Void>
+ var foo: ((Int) -> Void)?Mark unused function arguments with _.
| Option | Description |
|---|---|
--stripunusedargs |
"closure-only", "unnamed-only" or "always" (default) |
Examples
- func foo(bar: Int, baz: String) {
print("Hello \(baz)")
}
+ func foo(bar _: Int, baz: String) {
print("Hello \(baz)")
}- func foo(_ bar: Int) {
...
}
+ func foo(_: Int) {
...
}- request { response, data in
self.data += data
}
+ request { _, data in
self.data += data
}Use Void for type declarations and () for values.
| Option | Description |
|---|---|
--empty |
How empty values are represented: "void" (default) or "tuple" |
Examples
- let foo: () -> ()
+ let foo: () -> Void- let bar: Void -> Void
+ let bar: () -> Void- let baz: (Void) -> Void
+ let baz: () -> Void- func quux() -> (Void)
+ func quux() -> VoidWrap lines that exceed the specified maximum width.
| Option | Description |
|---|---|
--maxwidth |
Maximum length of a line before wrapping. defaults to "none" |
--nowrapoperators |
Comma-delimited list of operators that shouldn't be wrapped |
Align wrapped function arguments or collection elements.
| Option | Description |
|---|---|
--wraparguments |
Wrap all arguments: "before-first", "after-first", "preserve" |
--wrapparameters |
Wrap func params: "before-first", "after-first", "preserve" |
--wrapcollections |
Wrap array/dict: "before-first", "after-first", "preserve" |
--closingparen |
Closing paren position: "balanced" (default) or "same-line" |
Examples
NOTE: For backwards compatibility with previous versions, if no value is
provided for --wrapparameters, the value for --wraparguments will be used.
--wraparguments before-first
- foo(bar: Int,
- baz: String)
+ foo(
+ bar: Int,
+ baz: String
+ )- class Foo<Bar,
- Baz>
+ class Foo<
+ Bar,
+ Baz
+ >--wrapparameters after-first
- func foo(
- bar: Int,
- baz: String
- ) {
...
}
+ func foo(bar: Int,
+ baz: String) {
...
}--wrapcollections before-first:
- let foo = [bar,
baz,
- quuz]
+ let foo = [
+ bar,
baz,
+ quuz
+ ]Prefer constant values to be on the right-hand-side of expressions.