Swift Tips #34 - defer

preview_player
Показать описание
#iOS #swift #softwaredeveloper #iosdeveloper

Thank you for watching this video 🙌

•••••••••••• Music By •••••••••••••
"Picket Fences''
Jay Man - OurMusicBox
Рекомендации по теме
Комментарии
Автор

Did you find this tip useful? Are you planning on using it in your apps? Let me know in the comments 🚀

v_pradeilles
Автор

Your explanation of the drawbacks are super helpful. Thanks

keithweiss
Автор

Something like the Python "with" statement would be nice.

JumpingCow
Автор

I used defer yesterday! My function, which was a button press handler, had several exit paths since I had to do something different based on an AB test value. I used defer to ensure that my analytics code will get called no matter what.

hellaandrew
Автор

I'm a bit surprised that common things like file handling don't have a built-in closure-based API, along the lines of:

```
extension FileHandle {
public static func forReading(atPath: String, handler: (FileHandle?) throws -> Void) rethrows {
let file = FileHandle(forReadingAtPath: atPath)
defer { file?.closeFile() }
try handler(file)
}
}

try "~/temp.txt") { file in
guard let data = try? file?.readToEnd() else { return }
// use the data
}
```

Obviously, sometimes you keep files around longer than a single function call so you need the alternateive too, but it's a pretty common usecase.

DavidPetersonAU
visit shbcf.ru