【问题标题】:Compile error on Property Wrapper in Swift 5.1Swift 5.1 中的 Property Wrapper 编译错误
【发布时间】:2020-01-21 08:12:26
【问题描述】:

我正在研究 Swift 中的属性包装器,但我似乎错过了一些东西。

这就是我为我们使用的依赖注入框架编写属性包装器的方式:

@propertyWrapper
struct Inject<Value> {
    var _value: Value

    var wrappedValue: Value {
        get {
            return _value
        }
        set {
            _value = newValue
        }
    }

    init(_ container: Container = AppContainer.shared) {
        do {
            _value = try container.resolve(Value.self)
        } catch let e {
            fatalError(e.localizedDescription)
        }
    }
}

但是当我像下面这样在我的类中使用它时,我得到一个编译错误。我见过很多例子,对我来说做完全相同的事情,但可能存在一些差异。

class X: UIViewController {
    @Inject var config: AppConfiguration

    ....

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        config.johnDoSomething() // Compile error: 'AppConfiguration' is not convertible to 'AppConfiguration?'
    }
}

几天前,我发现 Xcode 在通用属性包装器方面存在编译问题,但我再也找不到它了。我不确定这是否相关,但也许 SO 上的某个人可以帮助我。

使用 Xcode 11.3.1

根据要求,特此声明(操场上的一个文件):

import UIKit

/// This class is only to mimick the behaviour of our Dependency Injection framework.
class AppContainer {
    static let shared = AppContainer()

    var index: [Any] = ["StackOverflow"]

    func resolve<T>(_ type: T.Type) -> T {
        return index.first(where: { $0 as? T != nil }) as! T
    }
}

/// Definition of the Property Wrapper.
@propertyWrapper
struct Inject<Value> {
    var _value: Value

    var wrappedValue: Value {
        get {
            return _value
        }
        set {
            _value = newValue
        }
    }

    init(_ container: AppContainer = AppContainer.shared) {
        _value = container.resolve(Value.self)
    }
}

/// A very minimal case where the compile error occurs.
class X {
    @Inject var text: String

    init() { }
}

【问题讨论】:

标签: swift dependency-injection swift5.1 property-wrapper


【解决方案1】:

只处理你的“reprex”:

改变

@Inject var text: String

@Inject() var text: String

【讨论】:

  • 谢谢,这行得通!我还有另一个错误导致 PW 无法正常工作。但这与在 @objc 函数中使用 AppConfiguration 变量有关。不知道为什么这不起作用,但至少它现在已经修复了。
  • 您的“reprex”中没有 AppConfiguration,这就是我要处理的全部内容。您所犯的错误与显式和隐式初始化程序如何为属性包装器工作有关。
猜你喜欢
  • 2020-03-17
  • 2022-01-07
  • 1970-01-01
  • 1970-01-01
  • 2014-04-15
  • 2020-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多