Property wrappers are now supported for local variables
About 2 min
Property wrappers are now supported for local variables 관련
HACKING WITH SWIFT
What's new in Swift?
Property wrappers are now supported for local variables | Changes in Swift 5.4
Property wrappers are now supported for local variables
Available from Swift 5.4
Property wrappers were first introduced in Swift 5.1 as a way of attaching extra functionality to properties in an easy, reusable way, but in Swift 5.4 their behavior got extended to support using them as local variables in functions.
For example, we could create a property wrapper that ensures its value never goes below zero:
@propertyWrapper struct NonNegative<T: Numeric & Comparable> {
var value: T
var wrappedValue: T {
get { value }
set {
if newValue < 0 {
value = 0
} else {
value = newValue
}
}
}
init(wrappedValue: T) {
if wrappedValue < 0 {
self.value = 0
} else {
self.value = wrappedValue
}
}
}
And from Swift 5.4 onwards we can use that property wrapper inside a regular function, rather than just attaching to a property. For example, we might write a game where our player can gain or lose points, but their score should never go below 0:
func playGame() {
@NonNegative var score = 0
// player was correct
score += 4
// player was correct again
score += 8
// player got one wrong
score -= 15
// player got another one wrong
score -= 16
print(score)
}
playGame()
Other Changes in Swift 5.4
Improved implicit member syntax | Changes in Swift 5.4
Improved implicit member syntax
Multiple variadic parameters in functions | Changes in Swift 5.4
Multiple variadic parameters in functions
Local functions now support overloading | Changes in Swift 5.4
Local functions now support overloading
Creating variables that call a function of the same name | Changes in Swift 5.4
Creating variables that call a function of the same name
Result builders | Changes in Swift 5.4
Result builders
Packages can now declare executable targets | Changes in Swift 5.4
Packages can now declare executable targets