Section 5/91 menit
5. Noncopyable dengan Generics
5. Noncopyable dengan Generics
swift
// Generic function yang menerima noncopyable type
func withResource<R: ~Copyable, Result>(
_ resource: consuming R,
body: (borrowing R) throws -> Result
) rethrows -> Result {
defer { _ = consume resource } // cleanup setelah body
return try body(resource)
}
// Penggunaan:
let result = withResource(FileHandle(path: "/tmp/data.txt")!) { handle in
handle.read(count: 100)
}
// FileHandle otomatis di-close setelah withResource selesai