将现有实例变量包装在变异的PropertyWrapper中

时间:2019-10-25 16:07:57

标签: swift generics

我实际上是在尝试使@PropertyWrapper充当exisitng私有实例成员的获取器和设置器。我下面是我的在制品。问题在于,由于无法访问self,因此无法引用实例成员。包装器不能偷懒,并且使私人成员变得懒惰也无济于事。我有这个线程(https://twitter.com/jckarter/status/1161298507527000064)和快速发展提案的这一部分(https://github.com/apple/swift-evolution/blob/master/proposals/0258-property-wrappers.md#referencing-the-enclosing-self-in-a-wrapper-type),但我只是不明白。有什么建议吗?

@propertyWrapper
struct PrivateWrapper<MemberOwner: AnyObject, MemberListener> {
    var privateVar: MemberOwner
    var member: ReferenceWritableKeyPath<MemberOwner, MemberListener>

    var wrappedValue: MemberListener {
        get {
            return privateVar[keyPath: member]
        }
        mutating set {
            privateVar[keyPath: member] = newValue
        }
    }
}

class A {
    var memberA: String
    var memberB: Int

    init(_ a: String, _ b: Int) {
        memberA = a
        memberB = b
    }
}

class B {
    private var aInst = A("Hello", 0)
    // Both wrappers get the following error:
    // "Cannot use instance member 'aInst' within property initializer; 
    // property initializers run before 'self' is available"
    @PrivateWrapper(privateVar: aInst, member: \A.memberA) var newAString: String
    @PrivateWrapper(privateVar: aInst, member: \A.memberB) var newBInt: Int 
}

0 个答案:

没有答案