简体   繁体   English

在 Swift 属性包装器中公开字典

[英]Exposing dictionary in Swift property wrappers

I have an internal dictionary that I don't want to expose to the user.我有一个不想向用户公开的内部字典。 Instead, I expose only certain values using properties, like this:相反,我只使用属性公开某些值,如下所示:

public var artist: String? {
  get {
     return items["artist"]
  }
  set {
     items["artist"] = newValue
  }
}

//...so on for another 20 or so items

As you can imagine, this ends up getting repeated quite a lot.可以想象,这最终会重复很多次。 I was thinking that property wrappers would be a nice way to clean this up - however, it's not possible to pass items directly to the wrapper, since property wrappers are created before init (so self would not be accessible).我在想属性包装器将是清理它的好方法 - 但是,不可能将items直接传递给包装器,因为属性包装器是在init之前创建的(因此无法访问self )。

Is there a way around this, or is this just one of the limitations of propertyWrappers?有没有办法解决这个问题,或者这只是 propertyWrappers 的限制之一?

You could build a generic solution.您可以构建一个通用解决方案。 I did one, but you can probably improve it:我做了一个,但你可能可以改进它:

    class PropertyWrapper {
    
    private var items: [String: Any] = ["artist": "some dude"]
    
    enum Key: String {
        case artist
    }
    
    func getItem<T: Any>(key: Key) -> T {
        guard let item = items[key.rawValue] as? T else {
            preconditionFailure("wrong type asked for")
        }
        return item
    }
    
    func setItem(value: Any, key: Key) {
        items[key.rawValue] = value
    }
}

class GetValueClass {
    
    func getValue() {
        let wrapper = PropertyWrapper()
        let value: String = wrapper.getItem(key: .artist)
    }
}

class SetValueClass {
    
    func setValue() {
        let wrapper = PropertyWrapper()
        wrapper.setItem(value: "some", key: .artist)
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM