Section 8/111 menit
8. Kapan Harus Digunakan
8. Kapan Harus Digunakan
Gunakan borrowing ketika:
1. Fungsi hanya membaca nilai (pure read)
swift
// Apapun yang hanya "inspect" atau "compute from" tanpa menyimpan
func serialize(data: borrowing UserProfile) -> Data { ... }
func validate(form: borrowing RegistrationForm) throws { ... }
func checksum(buffer: borrowing [UInt8]) -> UInt32 { ... }
func render(scene: borrowing Scene3D) -> UIImage { ... }
2. Fungsi yang sering dipanggil dengan nilai yang sama
swift
// Dipanggil berulang — borrowing mencegah copy berulang
func render(frame: borrowing AnimationFrame) {
// dipanggil 60 kali per detik — tanpa borrowing: 60 copies per detik
}
3. Large value types yang mahal untuk di-copy
swift
struct MLModel {
var weights: [[Float]] // bisa ratusan MB
}
func inference(model: borrowing MLModel, input: Tensor) -> Tensor {
// model tidak di-copy — sangat penting untuk performa
}
Gunakan consuming ketika:
1. Builder pattern
swift
// Setiap step menciptakan nilai baru
consuming func withOption(_ option: Option) -> Self { ... }
consuming func build() -> Product { ... }
2. Resource transfer yang jelas
swift
// Memperjelas bahwa setelah ini, caller tidak boleh pakai lagi
consuming func submit(_ job: Job) async { ... }
consuming func send(_ message: Message) async throws { ... }
3. Pipeline processing
swift
// Setiap tahap mengambil alih dan menghasilkan nilai baru
consuming func filtered(by predicate: Predicate) -> DataSet { ... }
consuming func sorted(by comparator: Comparator) -> DataSet { ... }
consuming func limited(to count: Int) -> DataSet { ... }
4. Noncopyable types — WAJIB
swift
struct FileHandle: ~Copyable { }
func process(handle: consuming FileHandle) { } // wajib karena ~Copyable