Home / Market / write swift

write swift

How to write modern Swift well — modeling with value types, Swift 6 data-race safety and approachable concurrency (@concurrent, main-actor-by-default, actors, task groups), protocols and generics (some vs any), API design, performance and ARC, Swift Testing, macros, and the modern language features agents don't know about yet. Use when writing, reviewing, or migrating Swift, or when a concurrency error, a hang, a data race, a retain cycle, or a performance problem needs fixing.

skill★ 62803203970 dlskills.shMITInstall in CosmosUpstream Source

Documentation & Preview

--- name: write-swift description: How to write modern Swift well — modeling with value types, Swift 6 data-race safety and approachable concurrency (@concurrent, main-actor-by-default, actors, task groups), protocols and generics (some vs any), API design, performance and ARC, Swift Testing, macros, and the modern language features agents don't know about yet. Use when writing, reviewing, or migrating Swift, or when a concurrency error, a hang, a data race, a retain cycle, or a performance problem needs fixing.

---

Write Swift

Initial Response

When this skill is first invoked without a specific question, respond only with:

> I'm ready to help you write modern Swift, the way the language wants to be written.

Do not provide any other information until the user asks a question.

How to write Swift the way the language wants to be written, current through Swift 6.4.

Toolchain baseline: Swift 6.3 (current release as of August 2026). Everything here compiles on 6.3 unless marked ⚠, which flags unreleased Swift 6.4 features. Concurrency guidance assumes the Swift 6.2 model — if the project is on 6.1 or earlier, §3's rules about async and @concurrent do not apply.

The through-line: Swift is a progressive-disclosure language. Start with the simplest, most static, most single-threaded thing that works, and buy dynamism — concurrency, reference semantics, existentials, unsafe pointers — only where you can point at the reason. Every rule below is an application of that.

Model this hierarchy of defaults. Move down a level only with a reason you can state:

| Need | Reach for | Move down only when | | ------------ | ----------------------- | ---------------------------------------------------------- | | Data | struct / enum | you need identity, sharing, or inheritance | | Abstraction | concrete type | you have repeated code across types | | Polymorphism | some P (generic) | you need heterogeneous storage → any P | | Execution | main actor, synchronous | profiling shows a hang → async → @concurrent → actor | | Memory | Array, String | profiling shows the cost → InlineArray, Span | | Safety | safe API | C interop or a measured hot path → Unsafe* |

---

1. Model data with value types

Value types are the default in Swift, not a special case.

struct Material {                       // value semantics preserved
  var roughness: Double
  private var _texture: Texture         // a class

  var color: Color {
    get { _texture.color }
    set {
      if !isKnownUniquelyReferenced(&_texture) { _texture = Texture(copying: _texture) }
      _texture.color = newValue
    }
  }
}

Noncopyable types (~Copyable) express unique ownership: a file descriptor, a bank transfer, an open resource. Suppressing the copy turns "you must not run this twice" from an assertion into a compile error, and makes deinit on a struct meaningful. Mark the finishing method consuming so the compiler proves it's the last use. Parameter ownership becomes explicit: borrowing (read-only, the default), consuming (takes it away), inout/mutating (temporary write access).

---

2. Errors and optionals — make the failure paths visible

Swift error handling rests on three points: sources of error are marked so they can't surprise you; errors carry enough context to act on; and recoverable errors are different from programmer mistakes.

---

3. Concurrency: stay single-threaded until profiling says otherwise

This is the section agents get wrong most often, because the model changed in Swift 6.2.

Start every app entirely on the main thread. Single-threaded code goes a long way, and most apps never need to leave it.

The progression, in order. Do not skip steps.

  1. Single-threaded on the main actor. No concurrency at all. Fine for most apps.
  2. async/await to hide latency (network, disk). Still no concurrency of your own — SDK APIs like URLSession.data(from:) offload on your behalf.
  3. @concurrent to move _your_ expensive work off the main thread — only after Instruments shows a hang.
  4. actor to move _state_ off the main actor — only when too much main-actor state is forcing tasks to hop back constantly.

Turn on the right build settings first. Enable Approachable Concurrency in every project. For app modules and UI-facing modules, also set Default Actor Isolation to MainActor — it's the default for new app projects in Xcode 26, and it deletes most of your @MainActor annotations. In a package: swiftSettings: [.defaultIsolation(MainActor.self)]. Do not set main-actor-by-default for a general-purpose library — libraries should ship nonisolated APIs and let clients decide where work runs.

The rule that changed

In Swift 6.2, marking a function async does _not_ move it off the current actor. It runs where it was called from. This is what makes "the most natural code to write" data-race free by default.

nonisolated struct PhotoProcessor {          // decoupled from the main actor
  @concurrent                                // guaranteed to run in the background
  func process(_ data: Data) async -> ProcessedPhoto {
    async let sticker = extractSticker(data)  // two independent jobs, in parallel
    async let colors  = extractColors(data)
    return await ProcessedPhoto(sticker: sticker, colors: colors)
  }
}

Actor reentrancy

Actors guarantee mutual exclusion, not transactions. Between two awaits on the same actor, other work runs.

---

4. Sendable and sharing data

Sendable marks a type safe to share across isolation domains. The compiler checks it at every task and actor boundary.

When you hit a data-race error, work down this list:

  1. Don't share it. Move the shared object into a local so each concurrent job gets its own instance. (This is the fix for the overwhelming majority of real errors.)
  2. Make it a Sendable value type, so "sharing" is really copying.
  3. Isolate it to an actor — the main actor, or your own.
  4. Only then reach for Mutex/Atomic from the Synchronization module (store them in let properties), or @unchecked Sendable.

**Global and static variables are th