Bird
Raised Fist0
Swiftprogramming~20 mins

Property wrappers with configuration in Swift - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Swift Property Wrapper Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of a property wrapper with initial configuration
What is the output of this Swift code using a property wrapper with configuration?
Swift
import Foundation

@propertyWrapper
struct Clamped {
    private var value: Int
    private let range: ClosedRange<Int>

    init(wrappedValue: Int, _ range: ClosedRange<Int>) {
        self.range = range
        self.value = min(max(wrappedValue, range.lowerBound), range.upperBound)
    }

    var wrappedValue: Int {
        get { value }
        set { value = min(max(newValue, range.lowerBound), range.upperBound) }
    }
}

struct Player {
    @Clamped(0...100) var health: Int = 150
}

let player = Player()
print(player.health)
A100
B150
CRuntime error
D0
Attempts:
2 left
💡 Hint
Think about how the initial value is adjusted to fit the allowed range.
❓ Predict Output
intermediate
2:00remaining
Effect of changing wrappedValue in a configured property wrapper
What will be printed after modifying the wrappedValue in this Swift code?
Swift
import Foundation

@propertyWrapper
struct LimitedString {
    private var value: String
    private let maxLength: Int

    init(wrappedValue: String, maxLength: Int) {
        self.maxLength = maxLength
        self.value = String(wrappedValue.prefix(maxLength))
    }

    var wrappedValue: String {
        get { value }
        set { value = String(newValue.prefix(maxLength)) }
    }
}

struct Message {
    @LimitedString(maxLength: 5) var text: String = "HelloWorld"
}

var msg = Message()
msg.text = "SwiftProgramming"
print(msg.text)
A"SwiftProgramming"
B"Hello"
C"Swift"
D"HelloWorld"
Attempts:
2 left
💡 Hint
Check how the setter limits the string length.
🔧 Debug
advanced
2:00remaining
Identify the error in this property wrapper with configuration
What error does this Swift code produce when compiled?
Swift
import Foundation

@propertyWrapper
struct Positive {
    private var value: Int

    init(wrappedValue: Int) {
        if wrappedValue > 0 {
            value = wrappedValue
        }
    }

    var wrappedValue: Int {
        get { value }
        set { value = newValue > 0 ? newValue : 1 }
    }
}

struct Account {
    @Positive var balance: Int = -10
}

let acc = Account()
print(acc.balance)
APrints -10
BRuntime error: Index out of range
CPrints 1
DCompile-time error: 'value' used before being initialized
Attempts:
2 left
💡 Hint
Check if all paths in init assign 'value'.
❓ Predict Output
advanced
2:00remaining
Output of a property wrapper with projectedValue configuration
What is the output of this Swift code using a property wrapper with projectedValue?
Swift
import Foundation

@propertyWrapper
struct Logged<Value> {
    private var value: Value
    var projectedValue: String = ""

    init(wrappedValue: Value) {
        self.value = wrappedValue
        self.projectedValue = "Initialized with \(wrappedValue)"
    }

    var wrappedValue: Value {
        get { value }
        set {
            value = newValue
            projectedValue = "Changed to \(newValue)"
        }
    }
}

struct Config {
    @Logged var setting: Int = 10
}

var config = Config()
config.setting = 20
print(config.$setting)
A"Changed to 20"
B"Initialized with 10"
C20
DRuntime error
Attempts:
2 left
💡 Hint
Look at when projectedValue changes.
❓ Predict Output
expert
3:00remaining
Final value after multiple property wrapper assignments with configuration
What is the final printed value of 'score' after all assignments in this Swift code?
Swift
import Foundation

@propertyWrapper
struct ScoreLimiter {
    private var value: Int
    private let minScore: Int
    private let maxScore: Int

    init(wrappedValue: Int, min: Int, max: Int) {
        self.minScore = min
        self.maxScore = max
        self.value = min(max(wrappedValue, min), max)
    }

    var wrappedValue: Int {
        get { value }
        set { value = min(max(newValue, minScore), maxScore) }
    }
}

struct Game {
    @ScoreLimiter(min: 0, max: 50) var score: Int = 60
}

var game = Game()
game.score = -10
game.score = 30
game.score = 100
print(game.score)
A30
B50
C60
D0
Attempts:
2 left
💡 Hint
Remember the property wrapper clamps values on assignment.

Practice

(1/5)
1. What is the main purpose of using property wrappers with configuration in Swift?
easy
A. To automatically generate UI elements
B. To create new data types from scratch
C. To replace functions with variables
D. To add reusable behavior to properties with customizable settings

Solution

  1. Step 1: Understand property wrappers

    Property wrappers add extra behavior to properties, like validation or formatting.
  2. Step 2: Understand configuration

    Configuration lets you customize how the wrapper behaves for each property.
  3. Final Answer:

    To add reusable behavior to properties with customizable settings -> Option D
  4. Quick Check:

    Property wrappers + configuration = reusable, customizable behavior [OK]
Hint: Think: reusable behavior + custom settings [OK]
Common Mistakes:
  • Confusing property wrappers with new data types
  • Thinking wrappers replace functions
  • Assuming wrappers auto-generate UI
2. Which of the following is the correct syntax to declare a property wrapper with a configuration parameter in Swift?
easy
A. @propertyWrapper struct Wrapper { var wrappedValue: Int; init(wrappedValue: Int, config: Bool) { self.wrappedValue = wrappedValue } }
B. @propertyWrapper struct Wrapper { var wrappedValue: Int }
C. struct Wrapper { var wrappedValue: Int; init(config: Bool) { self.wrappedValue = 0 } }
D. @propertyWrapper struct Wrapper { var wrappedValue: Int; func config() {} }

Solution

  1. Step 1: Identify property wrapper syntax

    Property wrappers use @propertyWrapper and must have wrappedValue.
  2. Step 2: Check for configuration parameter

    Configuration is passed via an initializer with extra parameters besides wrappedValue.
  3. Final Answer:

    @propertyWrapper struct Wrapper { var wrappedValue: Int; init(wrappedValue: Int, config: Bool) { self.wrappedValue = wrappedValue } } -> Option A
  4. Quick Check:

    Property wrapper + init with config = @propertyWrapper struct Wrapper { var wrappedValue: Int; init(wrappedValue: Int, config: Bool) { self.wrappedValue = wrappedValue } } [OK]
Hint: Look for @propertyWrapper + init with config param [OK]
Common Mistakes:
  • Missing @propertyWrapper attribute
  • No initializer with config parameter
  • Using functions instead of init for config
3. Consider this Swift code using a property wrapper with configuration:
@propertyWrapper
struct Clamped {
    private var value: Int
    private let range: ClosedRange<Int>

    var wrappedValue: Int {
        get { value }
        set { value = min(max(newValue, range.lowerBound), range.upperBound) }
    }

    init(wrappedValue: Int, range: ClosedRange<Int>) {
        self.range = range
        self.value = min(max(wrappedValue, range.lowerBound), range.upperBound)
    }
}

struct Example {
    @Clamped(range: 1...10) var number: Int = 5
}

var ex = Example()
ex.number = 15
print(ex.number)
What is the output when this code runs?
medium
A. 10
B. 5
C. 15
D. 1

Solution

  1. Step 1: Understand the Clamped wrapper behavior

    The wrapper clamps the value between the given range (1 to 10).
  2. Step 2: Analyze the assignment and print

    Assigning 15 triggers clamping to upper bound 10, so print outputs 10.
  3. Final Answer:

    10 -> Option A
  4. Quick Check:

    Value clamped to 10 [OK]
Hint: Remember clamping limits values to range [OK]
Common Mistakes:
  • Expecting original value 15 to print
  • Confusing initial value 5 with final
  • Ignoring clamping logic in setter
4. This Swift code attempts to use a property wrapper with configuration but causes a compile error:
@propertyWrapper
struct Limited {
    var wrappedValue: Int
    let max: Int

    init(max: Int) {
        self.max = max
        self.wrappedValue = 0
    }
}

struct Data {
    @Limited(max: 100) var score: Int = 50
}
What is the main reason for the error?
medium
A. Cannot assign default value to score when using wrapper
B. Missing init(wrappedValue:max:) initializer to accept initial value
C. Property wrapper cannot have stored properties
D. The max property must be var, not let

Solution

  1. Step 1: Check property wrapper initializer requirements

    When using a default value on a wrapped property, the wrapper needs an initializer init(wrappedValue:max:) to accept it.
  2. Step 2: Identify missing initializer

    The code only has init(max:), so compiler cannot match score: Int = 50.
  3. Final Answer:

    Missing init(wrappedValue:max:) initializer to accept initial value -> Option B
  4. Quick Check:

    Init must accept wrappedValue when default given [OK]
Hint: Add init(wrappedValue:..., config...) for default values [OK]
Common Mistakes:
  • Thinking stored properties are disallowed
  • Believing default value assignment is invalid
  • Confusing let/var for causing error
5. You want to create a property wrapper Validated that checks a string against a minimum length and a regular expression pattern, both configurable. Which approach correctly supports this configuration and usage?
@propertyWrapper
struct Validated {
    private var value: String
    private let minLength: Int
    private let pattern: String

    var wrappedValue: String {
        get { value }
        set {
            if newValue.count >= minLength && newValue.range(of: pattern, options: .regularExpression) != nil {
                value = newValue
            } else {
                value = ""
            }
        }
    }

    // What initializer should be here?
}

struct User {
    @Validated(minLength: 5, pattern: "^[a-zA-Z]+$") var username: String = ""
}
hard
A. init() { self.minLength = 0; self.pattern = ".*"; self.value = "" }
B. init(minLength: Int, pattern: String) { self.minLength = minLength; self.pattern = pattern; self.value = "" }
C. init(wrappedValue: String, minLength: Int, pattern: String) { self.minLength = minLength; self.pattern = pattern; self.value = wrappedValue }
D. init(wrappedValue: String) { self.minLength = 0; self.pattern = ".*"; self.value = wrappedValue }

Solution

  1. Step 1: Understand usage with default value and config

    The property username has a default value and two config parameters, so the wrapper needs an initializer accepting all three.
  2. Step 2: Match initializer signature

    Only an initializer with wrappedValue, minLength, and pattern parameters can initialize all properties correctly.
  3. Final Answer:

    init(wrappedValue: String, minLength: Int, pattern: String) { self.minLength = minLength; self.pattern = pattern; self.value = wrappedValue } -> Option C
  4. Quick Check:

    Init must accept wrappedValue + config params [OK]
Hint: Init must accept wrappedValue plus all config parameters [OK]
Common Mistakes:
  • Omitting wrappedValue in initializer
  • Not initializing all stored properties
  • Using init without parameters when config is needed
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard