- andOperator
- anyObjectProtocol
- blankLinesAroundMark
- blankLinesAtEndOfScope
- blankLinesAtStartOfScope
- blankLinesBetweenScopes
- braces
- consecutiveBlankLines
- consecutiveSpaces
- duplicateImports
- elseOnSameLine
- emptyBraces
- fileHeader
- hoistPatternLet
- indent
- isEmpty
- linebreakAtEndOfFile
- linebreaks
- numberFormatting
- ranges
- 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
- wrapArguments
Replaces the && operator with a comma inside if, guard and 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 {Replaces class with AnyObject in protocol definitions, as recommended in modern Swift guidelines.
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.
Adds a blank line before and after each MARK: comment.
| Option | Description |
|---|---|
--linebreaks |
linebreak character to use. "cr", "crlf" or "lf" (default) |
Examples
func foo() {
// foo
}
// MARK: bar
func bar() {
// bar
}
func foo() {
// foo
}
+
// MARK: bar
+
func bar() {
// bar
}Removes trailing blank lines from inside braces, brackets, parens or chevrons.
Examples
func foo() {
// foo
-
}
func foo() {
// foo
} array = [
foo,
bar,
baz,
-
]
array = [
foo,
bar,
baz,
]Removes leading blank lines from inside braces, brackets, parens or chevrons.
Examples
func foo() {
-
// foo
}
func foo() {
// foo
} array = [
-
foo,
bar,
baz,
]
array = [
foo,
bar,
baz,
]Adds a blank line before each class, struct, enum, extension, protocol or function.
| Option | Description |
|---|---|
--linebreaks |
linebreak character to use. "cr", "crlf" or "lf" (default) |
Examples
func foo() {
// foo
}
func bar() {
// bar
}
var baz: Bool
var quux: Int
func foo() {
// foo
}
+
func bar() {
// bar
}
+
var baz: Bool
var quux: IntImplements K&R or Allman-style braces.
| Option | Description |
|---|---|
--allman |
use allman indentation style. "true" or "false" (default) |
--linebreaks |
linebreak character to use. "cr", "crlf" or "lf" (default) |
Examples
- if x
- {
// foo
}
- else
- {
// bar
}
+ if x {
// foo
}
+ else {
// bar
}Reduces multiple sequential blank lines to a single blank line.
Examples
func foo() {
let x = "bar"
-
print(x)
}
func foo() {
let x = "bar"
print(x)
}Reduces a sequence of spaces to a single space.
Examples
- let foo = 5
+ let foo = 5Removes duplicate import statements.
Examples
import Foo
import Bar
- import Foo import B
#if os(iOS)
import A
- import B
#endifControls whether an else, catch or while keyword after a } appears on the same line.
| Option | Description |
|---|---|
--elseposition |
placement of else/catch. "same-line" (default) or "next-line" |
--allman |
use allman indentation style. "true" or "false" (default) |
--linebreaks |
linebreak character to use. "cr", "crlf" or "lf" (default) |
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
}Removes all white space between otherwise empty braces.
Examples
- func foo() {
-
- }
+ func foo() {}Allows the replacement or removal of Xcode source file comment headers.
| Option | Description |
|---|---|
--header |
header comments. "strip", "ignore", or the text you wish use |
--linebreaks |
linebreak character to use. "cr", "crlf" or "lf" (default) |
Moves let or var bindings inside patterns to the start of the expression (or vice-versa).
| 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
}Adjusts leading whitespace based on scope and line wrapping.
| Option | Description |
|---|---|
--indent |
number of spaces to indent, or "tab" to use tabs |
--indentcase |
indent cases inside a switch. "true" or "false" (default) |
--comments |
indenting of comment bodies. "indent" (default) or "ignore" |
--ifdef |
#if indenting. "indent" (default), "no-indent" or "outdent" |
--trimwhitespace |
trim trailing space. "always" (default) or "nonblank-lines" |
--linebreaks |
linebreak character to use. "cr", "crlf" or "lf" (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
}Replaces count == 0 checks with isEmpty, which is preferred for performance reasons (especially for Strings where count has O(n) complexity).
Examples
- if foo.count == 0 {
+ if foo.isEmpty {
- if foo.count > 0 {
+ if !foo.isEmpty {
- if foo?.count == 0 {
+ if foo?.isEmpty == true {Ensures that the last line of the file is empty.
| Option | Description |
|---|---|
--linebreaks |
linebreak character to use. "cr", "crlf" or "lf" (default) |
Normalizes all linebreaks to use the same character.
| Option | Description |
|---|---|
--linebreaks |
linebreak character to use. "cr", "crlf" or "lf" (default) |
Handles case and grouping of number 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 or "none", "ignore". default: 4,8 |
--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.123Controls the spacing around range operators.
| Option | Description |
|---|---|
--ranges |
spacing for ranges. "spaced" (default) or "no-space" |
Examples
- for i in 0..<5 {}
+ for i in 0 ..< 5 {}- if (0...5).contains(i) {}
+ if (0 ... 5).contains(i) {}Removes unnecessary escaping of identifiers using backticks, e.g. in cases where the escaped word is not a keyword, or is not ambiguous in that context.
Examples
- let `infix` = bar
+ let infix = bar- func foo(with `default`: Int) {}
+ func foo(with default: Int) {}Removes redundant break statements from inside switch cases.
Examples
switch foo {
case bar:
print("bar")
- break
default:
print("default")
- break
}Removes access control level keywords from extension members when the access level matches the extension itself.
Examples
public extension URL {
- public func queryParameter(_ name: String) -> String { ... }
}
public extension URL {
+ func queryParameter(_ name: String) -> String { ... }
}Replaces fileprivate access control keyword with private when they are equivalent, e.g. for top-level constants, functions or types within a file.
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)
}
}Removes unnecessary get { } clauses from inside read-only computed properties.
Examples
var foo: Int {
- get {
- return 5
- }
}
var foo: Int {
+ return 5
}Removes unnecessary init when instantiating types.
Examples
- String.init("text")
+ String("text")Removes redundant let or var from ignored variables in bindings (which is a warning in Xcode).
Examples
- let _ = foo()
+ _ = foo()Removes redundant let error from catch statements, where it is declared implicitly.
Examples
- do { ... } catch let error { log(error) }
+ do { ... } catch { log(error) }Removes unnecessary nil initialization of Optional vars (which are nil by default anyway).
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? = 0Removes unnecessary @objc annotation from properties and functions.
Examples
- @objc @IBOutlet var label: UILabel!
+ @IBOutlet var label: UILabel!- @IBAction @objc func goBack() {}
+ @IBOutlet func goBack() {}- @objc @NSManaged private var foo: String?
+ @NSManaged private var foo: String?Removes unnecessary parens from expressions and branch conditions.
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 = { ... }()Removes redundant pattern matching arguments for ignored variables.
Examples
- if case .foo(_, _) = bar {}
+ if case .foo = bar {}- let (_, _) = bar
+ let _ = barRemoves raw string values from enum cases when they match the case name.
Examples
enum Foo: String {
- case bar = "bar"
case baz = "quux"
}
enum Foo: String {
+ case bar
case baz = "quux"
}Removes unnecessary return keyword from single-line closures.
Examples
- array.filter { return $0.foo == bar }
+ array.filter { $0.foo == bar }Adds or removes explicit self prefix from class and instance member references.
| 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, which is common enough that it is excluded 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
}Removes unnecessary Void return type from function declarations.
Examples
- func foo() -> Void {
// returns nothing
}
+ func foo() {
// returns nothing
}Removes semicolons at the end of lines, and (optionally) replaces inline semicolons with a linebreak.
| Option | Description |
|---|---|
--semicolons |
allow semicolons. "never" or "inline" (default) |
--linebreaks |
linebreak character to use. "cr", "crlf" or "lf" (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)Rearranges import statements so that they are sorted.
| Option | Description |
|---|---|
--importgrouping |
"testable-top", "testable-bottom" or "alphabetized" (default) |
--linebreaks |
linebreak character to use. "cr", "crlf" or "lf" (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
+ #endifContextually adds or removes space around { ... }.
Examples
- foo.filter{ return true }.map{ $0 }
+ foo.filter { return true }.map { $0 }- foo( {} )
+ foo({})Contextually adjusts the space around [ ... ].
Examples
- foo as[String]
+ foo as [String]- foo = bar [5]
+ foo = bar[5]Adds space around /* ... */ comments and before // comments, depending on the --comments option (indent (default) or ignore).
Examples
- let a = 5// assignment
+ let a = 5 // assignment- func foo() {/* no-op */}
+ func foo() { /* no-op */ }Removes the space around < ... >.
Examples
- Foo <Bar> ()
+ Foo<Bar>()Contextually adjusts the space around infix operators. Also adds or removes the space between an operator function declaration and its arguments.
| Option | Description |
|---|---|
--operatorfunc |
spacing for operator funcs. "spaced" (default) or "no-space" |
Examples
- foo . bar()
+ foo.bar()- a+b+c
+ a + b + c- func ==(lhs: Int, rhs: Int) -> Bool
+ func == (lhs: Int, rhs: Int) -> BoolContextually adjusts the space around ( ... ).
Examples
- init (foo)
+ init(foo)- switch(x){
+ switch (x) {Adds space inside { ... }.
Examples
- foo.filter {return true}
+ foo.filter { return true }Removes the space inside [ ... ].
Examples
- [ 1, 2, 3 ]
+ [1, 2, 3]Adds a space inside /* ... */ comments and at the start of // comments.
| Option | Description |
|---|---|
--comments |
indenting of comment bodies. "indent" (default) or "ignore" |
Examples
- let a = 5 //assignment
+ let a = 5 // assignment- func foo() { /*no-op*/ }
+ func foo() { /* no-op */ }Removes the space inside < ... >.
Examples
- Foo< Bar, Baz >
+ Foo<Bar, Baz>Removes the space inside ( ... ).
Examples
- ( a, b)
+ (a, b)Normalizes the order for property/function/class specifiers (public, weak, lazy, etc.).
Examples
- lazy public weak private(set) var foo: UIView?
+ public private(set) lazy weak var foo: UIView?- override public final func foo()
+ public final override func foo()- convenience private init()
+ private convenience init()Removes the weak specifier from @IBOutlet properties.
Examples
As per Apple's recommendation (https://developer.apple.com/videos/play/wwdc2015/407/).
- @IBOutlet weak var label: UILabel!
+ @IBOutlet var label: UILabel!Replaces `self` with self when using the common guard let `self` = self pattern for strongifying weak self references.
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.
Ensures that TODO:, MARK: and FIXME: comments include the trailing colon (else they're ignored by Xcode).
Examples
- /* TODO fix this properly */
+ /* TODO: fix this properly */- // MARK - UIScrollViewDelegate
+ // MARK: - UIScrollViewDelegateConverts the last closure argument in a function call to trailing closure syntax where possible (disabled by default because it can introduce ambiguity that prevents code from compiling).
Examples
- DispatchQueue.main.async(execute: {
// do stuff
- })
+ DispatchQueue.main.async {
// do stuff
+ }NOTE: Occasionally, using trailing closure syntax makes a function call ambiguous, and the compiler can't understand it. Since SwiftFormat isn't able to detect this in all cases, the trailingClosures rule is disabled by default, and must be manually enabled via the --enable trailingClosures option.
Adds or removes trailing commas from the last item in an array or dictionary literal.
| Option | Description |
|---|---|
--commas |
commas in collection literals. "always" (default) or "inline" |
Examples
let array = [
foo,
bar,
- baz
]
let array = [
foo,
bar,
+ baz,
]Removes the whitespace at the end of a line.
| Option | Description |
|---|---|
--trimwhitespace |
trim trailing space. "always" (default) or "nonblank-lines" |
Replaces Array, Dictionary and Optional types with their shorthand forms.
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)?Marks unused arguments in functions and closures with _ to make it clear they aren't used.
| 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) {
// no-op
}
+ func foo(_: Int) {
// no-op
}- request { response, data in
self.data += data
}
+ request { _, data in
self.data += data
}Standardizes the use of Void vs an empty tuple ().
| 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() -> VoidWraps function arguments and collection literals.
| Option | Description |
|---|---|
--wraparguments |
wrap function args. "before-first", "after-first", "preserve" |
--wrapcollections |
wrap array/dict. "before-first", "after-first", "preserve" |
--closingparen |
closing paren position, "balanced" (default) or "same-line" |
--indent |
number of spaces to indent, or "tab" to use tabs |
--trimwhitespace |
trim trailing space. "always" (default) or "nonblank-lines" |
--linebreaks |
linebreak character to use. "cr", "crlf" or "lf" (default) |
Examples
- func foo(bar: Int,
- baz: String) {
// foo function
}
+ func foo(
+ bar: Int,
+ baz: String
+ ) {
// foo function
}Or for --wrapcollections before-first:
- let foo = [bar,
baz,
- quuz]
+ let foo = [
+ bar,
baz,
+ quuz
]