Swift Formatter

Paste Swift source — a SwiftUI view, a model or a networking helper — and get it laid out the way swift-format would. Everything happens in your browser; no code is uploaded.

Input

Settings

History

Load from URL

What runs behind this page

The engine is swift-format (WASM): Apple’s official formatter from the swiftlang project, built on SwiftSyntax, the same parser library the Swift compiler uses. It is not the similarly named community tool SwiftFormat, and its output differs from that tool in places, so check which one your team runs before comparing results.

Because swift-format works from a full syntax tree, recent language features are understood: async/await, actor, result builders such as SwiftUI’s @ViewBuilder, property wrappers, macros like #Preview, and regex literals. The formatter:

  • splits statements separated by ; onto separate lines
  • normalises spacing around :, -> and operators
  • breaks long argument lists and closures at the line width
  • keeps guard / else and trailing closures in the idiomatic positions

Blank lines you wrote between declarations are kept (up to the configured maximum) rather than added or removed wholesale.

That last point is worth knowing before you paste a large file: swift-format respects much of your existing vertical structure. Two developers who group properties differently will still get different files, whereas line breaks inside long expressions are fully decided by the formatter. In practice this means diffs after formatting are small and focused on spacing, which makes the tool safe to adopt on an existing codebase one file at a time.

Options, defaults and keys

Swift has no format-specific options here; the indent and line-width settings in the toolbar become swift-format’s indentation and lineLength. swift-format’s own defaults are 2 spaces and 100 columns, and the toolbar starts at 2 spaces and 80, so only the width usually needs changing if you want to match a project without a .swift-format file. Choosing tabs switches indentation to one tab per level.

Use Ctrl/Cmd+Enter to run the formatter, Ctrl/Cmd+Shift+C to copy the output and Ctrl/Cmd+K to open the command palette. Ctrl/Cmd+Shift+M (minify) does not apply to source code like Swift.

Tips and limitations

Code must parse before it can be formatted. swift-format reports the first problem as line:column followed by a message such as “expected ‘}’ to end function”, which usually means a brace is missing somewhere above that point.

To keep a hand-aligned declaration untouched, add // swift-format-ignore on the line before it; // swift-format-ignore-file at the top skips the whole file. Lint-only rules (naming, access control, documentation) are not reported here — this page formats, it does not lint.

Formatting never changes behaviour, but it can change line numbers, which matters if you are matching a crash log. Format first, then symbolicate, or keep the original file side by side. When a Swift crash arrives as text, the stack trace formatter can help with traces from other languages, and the JSON formatter is the quickest way to read a Codable payload.

Examples

SwiftUI view body

Each view in the result builder gets its own line and the semicolons disappear.

Input
import SwiftUI
struct OrderRow:View{let order:Order
var body:some View{HStack{VStack(alignment:.leading){Text(order.id).font(.headline);Text(order.customer).foregroundStyle(.secondary)};Spacer();Text(order.total,format:.currency(code:"USD"))}.padding(.vertical,4)}}
Output
import SwiftUI

struct OrderRow: View {
  let order: Order
  var body: some View {
    HStack {
      VStack(alignment: .leading) {
        Text(order.id).font(.headline)
        Text(order.customer).foregroundStyle(.secondary)
      }
      Spacer()
      Text(order.total, format: .currency(code: "USD"))
    }.padding(.vertical, 4)
  }
}
Open this example in the tool

async throws function with guard

guard statements expand into multi-line else blocks and the string interpolation is left exactly as written.

Input
func fetchOrder(id:String) async throws->Order{guard let url=URL(string:"https://api.example.com/orders/\(id)") else{throw URLError(.badURL)};let (data,response)=try await URLSession.shared.data(from:url);guard (response as? HTTPURLResponse)?.statusCode==200 else{throw URLError(.badServerResponse)};return try JSONDecoder().decode(Order.self,from:data)}
Output
func fetchOrder(id: String) async throws -> Order {
  guard let url = URL(string: "https://api.example.com/orders/\(id)") else {
    throw URLError(.badURL)
  }
  let (data, response) = try await URLSession.shared.data(from: url)
  guard (response as? HTTPURLResponse)?.statusCode == 200 else {
    throw URLError(.badServerResponse)
  }
  return try JSONDecoder().decode(Order.self, from: data)
}
Open this example in the tool

Codable struct, width 100

At swift-format’s default width the computed property can stay compact while properties still move to separate lines.

Input
struct Invoice:Codable,Identifiable{let id:UUID;let number:String;let lines:[Line];var total:Decimal{lines.reduce(0){$0+$1.amount}}
struct Line:Codable{let sku:String;let amount:Decimal}}
Output
struct Invoice: Codable, Identifiable {
  let id: UUID
  let number: String
  let lines: [Line]
  var total: Decimal { lines.reduce(0) { $0 + $1.amount } }
  struct Line: Codable {
    let sku: String
    let amount: Decimal
  }
}
Open this example in the tool

Common errors and how to fix them

ErrorCauseFix
1:11: expected '}' to end functionA function body was opened and the closing brace is missing.Add } at the end of the function. The position given is where the parser reached the end of input.
1:14: expected ']' to end arrayAn array or dictionary literal is not closed.Close the literal with ]; check for a trailing element that was pasted without its bracket.
1:8: expected ')' to end parameter clauseA function signature has an unbalanced parenthesis.Close the parameter list before the return arrow or the opening brace.
1:22: expected '}' to end structA struct, class or enum declaration is missing its closing brace.Add the brace after the last member.

Frequently asked questions

Is this swift-format or SwiftFormat?

It is Apple’s swift-format from the swiftlang project. The community SwiftFormat tool by Nick Lockwood has different rules and options.

Can I use my .swift-format configuration file?

Not on this page. Only indentation and line length can be changed, which are the settings most projects customise.

Does it support SwiftUI and macros?

Yes. Result builders, property wrappers, macros and async/await all parse because swift-format uses SwiftSyntax.

Will it reorder my imports or members?

Members and declarations stay in the order you wrote them. Import statements are sorted alphabetically and followed by a blank line, as swift-format does by default.

Related tools