Assigning propertyWrapper
Hi, I am learning propertyWrappers in Swift last days and I found something strange on the internet. In this article https://nshipster.com/propertywrapper/
import Foundation
@propertyWrapper
struct CaseInsensitive<Value: StringProtocol> {
var wrappedValue: Value
}
extension CaseInsensitive: Comparable {
private func compare(_ other: CaseInsensitive) -> ComparisonResult {
wrappedValue.caseInsensitiveCompare(other.wrappedValue)
}
static func == (lhs: CaseInsensitive, rhs: CaseInsensitive) -> Bool {
lhs.compare(rhs) == .orderedSame
}
static func < (lhs: CaseInsensitive, rhs: CaseInsensitive) -> Bool {
lhs.compare(rhs) == .orderedAscending
}
static func > (lhs: CaseInsensitive, rhs: CaseInsensitive) -> Bool {
lhs.compare(rhs) == .orderedDescending
}
}
struct Account: Equatable {
@CaseInsensitive var name: String
init(name: String) {
$name = CaseInsensitive(wrappedValue: name)
}
}
There is assigning propertyWrapper to the name inside the init and it looks strange for me why author is trying to assign to the projectedValue ($) instead of use _name to talk with propertyWrapped instance...
Am I right that there should be:
init(name: String) {
_name = CaseInsensitive(wrappedValue: name)
}
?
NSHipster
Swift Property Wrappers
Swift property wrappers go a long way to making SwiftUI possible, but they may play an even more important role in shaping the future of the language as a whole.
2 Replies
That must be a typo in the article. $name produces an error and you’re right that _name works and makes sense.
Thanks @Valorie