Swift 5.1中Property Wrapper的编译错误 [英] Compile error on Property Wrapper in Swift 5.1

查看:59
本文介绍了Swift 5.1中Property Wrapper的编译错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在弄清楚Swift中的Property Wrappers,但是我似乎错过了一些东西.

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

几天前,我遇到了一个参考,该参考提到Xcode的Generic Property Wrappers存在编译问题,但现在找不到了.我不确定这是否有意义,但也许有人可以帮助我.

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.

使用Xcode 11.3.1

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

推荐答案

只需处理您的"reprex":

Just dealing with your "reprex":

更改

@Inject var text: String

@Inject() var text: String

这篇关于Swift 5.1中Property Wrapper的编译错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆