Compile error on Property Wrapper in Swift 5.1

别来无恙 提交于 2021-01-29 12:27:48

问题


I'm figuring out Property Wrappers in Swift, but I seem to miss something.

This is how I wrote a property wrapper for a dependency injection framework we use:

@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)
        }
    }
}

But when I use it in my class like below, I get a compile error. I've seen a lot of examples that to me do the exact same thing but probably there are some differences.

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?'
    }
}

I few days ago I came across a reference that Xcode had compile issues with Generic Property Wrappers, but I can't find it anymore. I'm not sure if that's relevant but maybe somebody on SO can help me out.

Using Xcode 11.3.1

As requested, hereby a reprex (one file in playground):

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() { }
}

回答1:


Just dealing with your "reprex":

Change

@Inject var text: String

to

@Inject() var text: String


来源:https://stackoverflow.com/questions/59836661/compile-error-on-property-wrapper-in-swift-5-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!