0
0
Swiftprogramming~20 mins

Custom validation property wrappers in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Swift Validation Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of a simple custom validation property wrapper
What is the output of this Swift code using a custom validation property wrapper?
Swift
import Foundation

@propertyWrapper
struct NonEmpty {
    private var value: String = ""
    var wrappedValue: String {
        get { value }
        set {
            if newValue.isEmpty {
                print("Empty string not allowed")
            } else {
                value = newValue
            }
        }
    }
}

struct User {
    @NonEmpty var name: String
}

var user = User()
user.name = ""
print(user.name)
user.name = "Alice"
print(user.name)
A
Empty string not allowed


Alice
B
Empty string not allowed


C


Alice
D
Empty string not allowed

Alice
Attempts:
2 left
💡 Hint
Look at how the setter handles empty strings and what is printed.
🧠 Conceptual
intermediate
1:30remaining
Purpose of custom validation property wrappers
What is the main purpose of using a custom validation property wrapper in Swift?
ATo improve the performance of property accessors
BTo allow properties to be accessed from multiple threads safely
CTo automatically validate and control the values assigned to properties
DTo convert properties into computed properties without storage
Attempts:
2 left
💡 Hint
Think about what validation means in everyday life.
🔧 Debug
advanced
2:30remaining
Identify the error in this custom validation property wrapper
What error will this Swift code produce when compiled?
Swift
@propertyWrapper
struct Positive {
    private var value: Int
    var wrappedValue: Int {
        get { value }
        set {
            if newValue > 0 {
                value = newValue
            } else {
                print("Value must be positive")
            }
        }
    }
}

struct Account {
    @Positive var balance: Int
}

let acc = Account()
print(acc.balance)
ARuntime error: Unexpected nil value
BError: Property 'value' not initialized before use
CError: Cannot assign to property 'balance' because it is a 'let' constant
DNo error, prints 0
Attempts:
2 left
💡 Hint
Check if all stored properties have initial values.
📝 Syntax
advanced
2:00remaining
Correct syntax for a property wrapper with projectedValue
Which option correctly defines a property wrapper with a projectedValue that returns a Bool indicating if the value is valid?
Swift
struct Length {
    private var value: String
    var wrappedValue: String {
        get { value }
        set { value = newValue }
    }
    var projectedValue: Bool {
        // returns true if length > 3
    }
}
Avar projectedValue: Bool { value.count > 3 }
Bvar projectedValue: Bool { return value.length > 3 }
Cvar projectedValue: Bool { value.count > 3 else false }
Dvar projectedValue: Bool { if value.count > 3 { true } }
Attempts:
2 left
💡 Hint
Use the correct property for string length and a simple expression.
🚀 Application
expert
3:00remaining
Using a custom validation property wrapper in a struct
Given this property wrapper, what will be the output of the following code?
Swift
@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 Settings {
    @Clamped(0...10) var volume: Int = 5
}

var s = Settings()
s.volume = 15
print(s.volume)
s.volume = -3
print(s.volume)
s.volume = 7
print(s.volume)
A
10
0
7
B
5
5
7
C
15
-3
7
D
10
-3
7
Attempts:
2 left
💡 Hint
The wrapper clamps values to the range 0 to 10.