Sendable e verificação de segurança entre threads
Marque os dados como Sendable , escreva closures @Sendable e escolha entre tipos de valor, atores e @unchecked Sendable para compartilhamento seguro entre threads.
Sendable e verificação de segurança entre threads é uma aula grátis de Swift Academy no CoddyKit. Esta é a aula 3 de 3. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Swift Academy, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Swift Academy inclui 3 aulas no total.
O que é Sendable?
Sendable é a forma do Swift de garantir que os dados possam ser passados com segurança entre tarefas ou atores concorrentes.
- A maioria das estruturas e enumerações é Sendable automaticamente.
- Classes não são Sendable por padrão.
- Use atores ou @unchecked Sendable (raramente, com segurança manual).
Tipos de valor são simples
Estruturas com membros Sendable são Sendable; passá-las entre tarefas é seguro.
// Value types with value-only stored properties are Sendable.
// They are safe to transfer across tasks.
struct Point: Sendable { let x: Int; let y: Int }
func shift(_ p: Point) -> Point { Point(x: p.x + 1, y: p.y + 1) }
// Use in parallel tasks
Task {
let p = Point(x: 1, y: 2)
async let a = shift(p)
async let b = shift(p)
let (p1, p2) = await (a, b)
print(p1, p2) // Point(x: 2, y: 3) Point(x: 2, y: 3)
}Classes: use atores
Atores tornam segura a semântica de referência entre tarefas ao serializar o acesso.
// Reference types (class) are not Sendable by default.
// Prefer actors to guard mutable state.
actor SafeCounter {
private var value = 0
func inc() { value += 1 }
func read() -> Int { value }
}
let counter = SafeCounter()
Task {
async let t1 = counter.inc()
async let t2 = counter.inc()
_ = await (t1, t2)
print(await counter.read()) // 2
}
// (Alternative) A plain class would need locks + @unchecked Sendable; see later.Fechamentos @Sendable
Marque os fechamentos como @Sendable quando eles puderem ser executados em outros executores. Evite capturar estado mutável não-Sendable.
// Some APIs require closures to be @Sendable so captured values are safe.
func doTwice(_ f: @Sendable () -> Int) -> Int { f() + f() }
let base = 10
// Capturing an immutable value (let) is fine for @Sendable closures.
let result = doTwice { base + 1 }
print(result) // 22
// Detached tasks also use @Sendable under the hood:
let t = Task.detached { () -> Int in
// Do not capture non-Sendable mutable state here.
return 5 * 5
}
Task { print(await t.value) }@unchecked Sendable (avançado)
@unchecked Sendable desativa as verificações do compilador. Use-o somente com sincronização interna rigorosa (bloqueios ou filas) e como último recurso.
import Foundation
// Only when you KNOW it is safe: wrap with a lock and mark @unchecked Sendable.
final class Box<T>: @unchecked Sendable {
private var value: T
private let lock = NSLock()
init(_ value: T) { self.value = value }
func read() -> T {
lock.lock(); defer { lock.unlock() }
return value
}
func write(_ newValue: T) {
lock.lock(); value = newValue; lock.unlock()
}
}
let shared = Box<Int>(0)
let a = Task.detached { shared.write(1) }
let b = Task.detached { shared.write(2) }
Task {
_ = await (a.value, b.value)
print(shared.read()) // 1 or 2 (last writer wins, but no data race)
}Boas práticas
Diretrizes:
- Prefira tipos de valor (compatíveis com Sendable).
- Use atores para o estado mutável compartilhado.
- Escreva fechamentos @Sendable; evite capturar valores mutáveis não-Sendable.
- Use @unchecked Sendable somente com sincronização rigorosa.
Significado de Sendable
Verificação rápida: O que Sendable garante?
Recapitulação
Recapitulação: Use Sendable para modelar a segurança entre tarefas, prefira atores ou tipos de valor, escreva fechamentos @Sendable e reserve @unchecked Sendable apenas para componentes internos bem sincronizados.
Perguntas Frequentes
A aula “Sendable e verificação de segurança entre threads” é grátis?
Sim — o texto completo de “Sendable e verificação de segurança entre threads” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Swift Academy, atualize para CoddyKit PRO. O curso de Swift Academy inclui 3 aulas no total.
O que vou aprender em “Sendable e verificação de segurança entre threads”?
Marque os dados como Sendable , escreva closures @Sendable e escolha entre tipos de valor, atores e @unchecked Sendable para compartilhamento seguro entre threads. Você pratica Swift Academy com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Swift Academy?
Nenhuma experiência prévia é necessária. Swift Academy no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 3 de 3.
Quanto tempo leva a aula “Sendable e verificação de segurança entre threads”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Swift Academy?
Sim. Cada aula de Swift Academy inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- TaskGroup para paralelismo
- Atores e isolamento de dados, nonisolated
- Sendable e verificação de segurança entre threads