首页 > 解决方案 > 为什么这个结构会隐藏 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我创建的类型的扩展。

这是为什么?

标签: iosswiftswift4swift5

解决方案


替换<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”


推荐阅读