ios - 为什么这个结构会隐藏 String 类型?
问题描述
我正在尝试了解属性包装器。
我有另一个关于 SO 的问题,我试图创建一个像这样的属性包装器:
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
}
}
}
那行不通,因为该行value.findReplace
显示错误
字符串类型的值?没有名字 findReplace
一旦有人建议我将 struct 行更改为
struct AdjustTextWithAppName {
整个事情开始起作用了。
为什么?我不明白为什么<String>
结构上的术语会影响String
我创建的类型的扩展。
这是为什么?
解决方案
替换<String>
为常见的泛型类型<T>
,您将立即看到问题
@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
}
}
}
现在这个错误更容易理解了
“T”类型的值没有成员“findReplace”
推荐阅读
- alfresco - Alfresco 从 PPTX 文件创建 PDF 再现
- r - 将多边形 shapefile 导出为 XY 顶点对列表
- neo4j - Neo4J 查询最常见的关系
- python - iPython:用 try/except 杀死一个 for 循环?
- python - 分配简单变量命名后的 KeyError
- python - 为什么当我尝试将元组输入到树视图时只有一半被读取
- php - 计算两列值不匹配的行数
- bootstrap-4 - 格式化 thymeleaf 表头,垂直对齐
- java - 关于如何在 Java 中构建我自己的 StringBuilder 类的建议?
- jquery - 用 Vue 复制 jQuery 的 slideDown()