Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to access the wrapped value of the property wrapper.
Swift
struct User {
@Logged var name: String
func printName() {
print(name[1])
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using .projectedValue instead of .wrappedValue
Trying to call the property as a function
Using array indexing syntax
✗ Incorrect
Use .wrappedValue to access the actual value stored by the property wrapper.
2fill in blank
mediumComplete the code to access the projected value of the property wrapper.
Swift
struct User {
@Logged var name: String
func printLog() {
print($name[1])
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using .wrappedValue instead of .projectedValue
Forgetting the $ prefix
Trying to call the property as a function
✗ Incorrect
Use .projectedValue to access the extra value or functionality the wrapper provides, accessed via the $ prefix.
3fill in blank
hardFix the error in accessing the wrapped value inside the property wrapper struct.
Swift
@propertyWrapper
struct Logged {
private var value: String
var [1]: String {
get { value }
set { value = newValue }
}
init(wrappedValue: String) {
self.value = wrappedValue
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using projectedValue instead of wrappedValue
Using a different property name like value or wrapped
✗ Incorrect
The property wrapper must define a property named wrappedValue to work correctly.
4fill in blank
hardFill both blanks to define the projectedValue property that returns a log string.
Swift
@propertyWrapper
struct Logged {
private var value: String
private(set) var log: String = ""
var wrappedValue: String {
get { value }
set {
value = newValue
log += "Value changed to \(newValue)\n"
}
}
var [1]: String {
return log
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Naming the property wrappedValue instead of projectedValue
Returning value instead of log
✗ Incorrect
The projectedValue property is named projectedValue and returns the log string.
5fill in blank
hardFill all three blanks to create a dictionary comprehension that maps property names to their wrapped values if the value is not empty.
Swift
struct User {
@Logged var firstName: String
@Logged var lastName: String
func nonEmptyProperties() -> [String: String] {
[
"firstName": $firstName[1],
"lastName": $lastName[2]
].filter { $0.value [3] "" }
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using .projectedValue instead of .wrappedValue
Using == instead of != in the filter
Forgetting to access wrappedValue
✗ Incorrect
Use .wrappedValue to get the actual value from the projected property, and filter where value is not equal to empty string.