Property Wrappers or How Swift decided to become Java 🙃

Last updated: 22 days ago

Swift 5.1 brought a new construct to the language: Property Wrappers. SwiftUI, for instance, relies heavily on it to provide its system of data-binding through annotations like @State, @EnvironmentObject, etc.

Unlike other language improvements, Codable for instance, Apple hasn’t restricted the use of this new feature to its own frameworks: any codebase is free to leverage it to implement custom property attributes that will suit its own specific needs.

While this is a great opportunity to factorise common behaviours throughout a project, one can still wonder: won’t it hurt code readability and predictability on the long run? Keeping code short is good, but if it’s achieved through a collection of arcane annotations, it might end up defying the original intent.

In this talk, I want to introduce what Property Wrappers are, give some example of how they can be leveraged, and try to provide some guidelines on when we they should or shouldn’t be use. The audience will learn about he basic use case of property: wrapping a raw value around a layer of business logic. But we'll also go into more involved applications, such as providing seamless interaction with the UserDefaults API or even synthesizing network calls (in a similar fashion to the Android API Retrofit).

Here are some code snippets, to give you some examples of what I'll show in my talk 👇

struct ChemicalSolution { @Clamping(0...14) var pH: Double = 7.0 }

struct UserDefaultsConfig { @UserDefault("hasseenapp_introduction", defaultValue: false) static var hasSeenAppIntroduction: Bool }

struct API { @GET(url: "https://samples.openweathermap.org/data/2.5/weather?id=2172797&appid=b6907d289e10d714a6e88b30761fae22") static var getCurrentWeather: Service }

Comments

UIKonf Friendly Commenter
2472d4eacadec4
22 days

Hi, this is supposed to be an anonymous call for proposals. Please remove information that identifies you.

Author
22 days

Oh ok. When I read the guidelines, I thought this kind of links to content closely related to the topic was fine ("That's fine and there's no need to go to great lengths to conceal your identity if it makes the proposal more difficult to write.")

But if it's an issue, no problem I'll remove the links.

Author
22 days

So I've tried to directly embed code examples in the proposal. The formatting doesn't look as great as I'd like, but they're short enough that they should still be readable 🙂

Log in to comment