@Once property wrapper

Hi all,

Thanks to SE-0293 it is now possible to add property wrappers to function and closure parameters. So I used this feature to create a very simple property wrapper called @Once to enforce that function parameters that accept a closure are called exactly once. This has something that has been previously discussed in this pitch.

This is quite useful to catch bugs where you forget to call the closure (i.e. say a completion handler) or accidentally end up calling it multiple times. By adding the @Once property wrapper, you'll get a runtime error if you make either of these mistakes.

Unfortunately, it's not as powerful as it could be if it was built into the language, and one of the limitations is that it does not work with non-escaping closures (since the closure needs to be temporarily stored into the property wrapper) so you will need to annotate it with @escaping even if it is unnecessary.

Still, I think there's some value in being able to use it. Most of my own use cases involve @escaping closures (ex: completion handler for delegate functions or backend API functions) so it's definitely useful in those scenarios for me. Recently, there was a bug in a production app that I am working on, which could've been discovered earlier if we were using @Once!

Anyhow, let me know what you think! You can find the code here and it's available as a Swift package that you can drop into your code base :slight_smile: You don't need to be on Swift 5.5 to use it, you can use it on older versions too where you might have properties with function types!

9 Likes

Interesting! What would that look like?

Ah sorry on the second thought it makes not much sense. :man_facepalming: The closure is available directly anyways and the PW is hidden by default. Never mind then.

Terms of Service

Privacy Policy

Cookie Policy