Property Wrappers II
Custom property wrappers.
Property Wrappers II
Custom property wrappers.
0
0
Checkbox to mark video as read
Mark as read

In our first chapter on Property wrappers we saw some SwiftUI native examples that not only allow you to encapsulate functionality that's commonly associated with properties, like @State, but they also allow you to add custom behaviors to properties without duplicating code.

Today we are going to explore how to write our custom Property wrappers to improve readability and maintainability.

Defining A Property Wrapper

In Swift we define it using the @propertyWrapper attribute and can apply it to properties in a class, struct, or enum. The core requirement for a property wrapper is a wrappedValue property that provides the underlying value.

Let's start with a basic example: a property wrapper that logs changes to a property whenever its value is modified.

@propertyWrapper
struct Validator { // 1
    private var value: String
    
    init(wrappedValue: String) { // 2
        self.value = wrappedValue
    }
    
    var wrappedValue: String {
        get { value }
        set {
            print("Email changed from \"\(value)\" to \"\(newValue)\"") // 3
            value = newValue
        }
    }
}

struct User { // 4
    @Validator var email: String
}

var user = User(email: "test")
user.email = "test@educaswift.com"
// Prints: Value changed from "test" to "test@educaswift.com"

Continue reading

Access to all the content with our plans.

Basic Plan

FREE

Start Now
  • Junior level content
  • Senior level content
  • Expert level content
  • Extra content
  • Question submissions
Monthly
Yearly

Plan logo

-

Unlimited access to the whole content

  • Junior level content
  • Senior level content
  • Expert level content
  • Extra content
  • Question submissions

Stripe secure payment methods
Plan logo

-

Unlimited access to the whole content

  • Junior level content
  • Senior level content
  • Expert level content
  • Extra content
  • Question submissions

Stripe secure payment methods
Plan logo

-

Solve your doubts at any level

  • Junior level content
  • Senior level content
  • Expert level content
  • Extra content
  • 2 Question submissions per week

Stripe secure payment methods
Plan logo

-

Solve your doubts at any level

  • Junior level content
  • Senior level content
  • Expert level content
  • Extra content
  • 2 Question submissions per week

Stripe secure payment methods

0 Comments

Join the community to comment
Sign Up
I have an account
Be the first to comment

Accept Cookies

We use cookies to collect and analyze information on site performance and usage, in order to provide you with better service.

Check our Privacy Policy