尝试为应该调整字符串的属性制作包装器 [英] Trying to make a wrapper for a property that should adjust a string
问题描述
我有这段代码需要让其他应用重复使用.
I have this code that I need to make reusable by other apps.
此代码显示存在本地化应用程序名称的消息.
This code shows messages where the localized app's name is present.
所以,我有这样的本地化字符串:
So, I have localized strings like this:
"DoYou" = "Do you really want to close $$$?";
"Quit" = "Quit $$$";
"Keep Running" = "Keep $$$ Running";
其中 $$$
必须在运行时替换为本地化应用的名称.
Where $$$
must be replaced with the localized app's name at run time.
因为我想了解属性包装器,我尝试创建了这个:
Because I want to learn about property wrappers, I have tried to create this one:
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
}
}
}
我在 replaced
行收到此错误:
I get this error on the replaced
line:
字符串类型的值?没有名字 findReplace
Value of type String? has no name
findReplace
我也试过用这条线
let replaced = value!.findReplace("$$$", withString: localizedAppName)
同样的错误...
该字符串可能多次包含应用程序名称.这就是为什么我有 String
的扩展.
The string may contain the app's name more than once. This is why I have that extension to String
.
推荐答案
为了解决这个问题,你的属性包装器不能有一个名为 String 的泛型类型,因为它掩盖了你的扩展所属的内置类型 String.所以将 struct
声明改为非泛型
To solve this your property wrapper can't have a genereic type named String because that shadows the built-in type String that your extension belongs to. So change the struct
declaration to not be generic
@propertyWrapper
struct AdjustTextWithAppName {
或将类型命名为其他名称
or name the type to something else
@propertyWrapper
struct AdjustTextWithAppName<T> {
并修复set
方法
set {
guard let str = newValue, let localizedAppName = Bundle.main.localizedInfoDictionary?["CFBundleName"] as? String else {
value = nil
}
value = str.findReplace(target: "$$$", withString: localizedAppName)
}
这篇关于尝试为应该调整字符串的属性制作包装器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!