I am trying to understand property wrappers.
I have another question of mine on SO, where I was trying to create a property wrapper like this:
extension String {
func findReplace(_ target: String, withString: String) -> String
{
return self.replacingOccurrences(of: target,
with: withString,
options: NSString.CompareOptions.literal,
range: nil)
}
}
@propertyWrapper
struct AdjustTextWithAppName<String> {
private var value: String?
init(wrappedValue: String?) {
self.value = wrappedValue
}
var wrappedValue: String? {
get { value }
set {
if let localizedAppName = Bundle.main.localizedInfoDictionary?["CFBundleName"] as? String {
let replaced = value.findReplace("$$$", withString: localizedAppName)
}
value = nil
}
}
}
That was not working because the line value.findReplace
was showing an error
Value of type String? has no name findReplace
As soon as someone suggested me to change the struct line to
struct AdjustTextWithAppName {
the whole thing started working.
Why? I cannot understand why <String>
term on the struct was shadowing the extension to the String
type I have created.
Why is that?
Replace <String>
with the common generic type <T>
and you'll see the issue immediately
@propertyWrapper
struct AdjustTextWithAppName<T> {
private var value: T?
init(wrappedValue: T?) {
self.value = wrappedValue
}
var wrappedValue: T? {
get { value }
set {
if let localizedAppName = Bundle.main.localizedInfoDictionary?["CFBundleName"] as? String {
let replaced = value.findReplace("$$$", withString: localizedAppName) // Value of type 'T' has no member 'findReplace'
}
value = nil
}
}
}
Now the error is more understandable
Value of type 'T' has no member 'findReplace'
I cannot understand why
<String>
term on the struct was shadowing the extension to theString
type I have created.
Why wouldn't it? You explicitly requested for there to be a generic type parameter to AdjustTextWithAppName
called String
. The compiler gave you precisely what you asked for.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.