Memory safety en Swift: ownership, exclusivity y accesos en conflicto

Los tipos marcados con ~Copyable no pueden copiarse implícitamente. El compilador garantiza que solo existe un propietario a la vez. Esto elimina una clase entera de bugs de doble liberación sin overhead en tiempo de ejecución:

struct Handle: ~Copyable {
    let descriptor: Int32
    init(_ fd: Int32) { self.descriptor = fd }
    consuming func cerrar() { close(descriptor); print("fd (descriptor) cerrado") }
}

func procesarHandle() {
    var h = Handle(42)
    // var h2 = h  // Error: Handle no es copiable
    h.cerrar()    // consuming: h no puede usarse despues
}

borrowing y consuming

struct Fichero: ~Copyable {
    private let fd: Int32
    init(fd: Int32) { self.fd = fd }
    borrowing  func leer()   -> String { "datos" }  // no consume
    consuming  func cerrar() { close(fd) }          // consume
    deinit { close(fd) }  // fallback si no se llamo cerrar()
}

COMPARTE ESTE ARTÍCULO

COMPARTIR EN FACEBOOK
COMPARTIR EN TWITTER
COMPARTIR EN LINKEDIN
COMPARTIR EN WHATSAPP