swift - 在 Swift 中通过下标访问单例属性

标签 swift singleton subscript kvc

我有一个单例类:

class Session {
  static let sharedInstance = Session()
  private init() {}
  // app properties
  var token: String!
  var promotions: JSON!
}

在一个网络类中,我有多个异步调用,我使用每个 url 的 map 函数触发它们:

let urls = [ "promotions": "http:..." ]

let results = urls.map { (k, url) in
  self.getFromApi(url, params: ["token" : token]) { response in
    guard response as? JSON != nil else { return }

    Session.sharedInstance[k] = response
    // the above should compile to Session.sharedInstance["promotions"] = response.
  }

问题在于尝试通过下标设置 sharedInstance 上的响应。我试图在 Singleton 上实现下标但无济于事:

subscript(property: Any) -> Any {
  get {
    return Session.sharedInstance[property]
  }
  set(newValue) {
    Session.sharedInstance[property] = newValue
  }
}

我也曾尝试通过遵守 NSObject 并使用 KVC 来放弃下标,但这也没有用,而且我失去了所有类型安全。

非常感谢任何帮助或建议。 提前致谢。

最佳答案

你可以让你的单例成为一个包类。您有一本字典,其中包含您的 JSON 或属性。其他一切都只是计算值。

class Session {
    static let sharedInstance = Session()
    private init() {}
    // app properties
    var token: String!

    private var fetchedJSON : [String:Any] = [:]

    var keys : [String] {
        return Array(fetchedJSON.keys)
    }

    // handy to do downcasts in here
    var promotions : JSON? {
        get {
            if let promotions = fetchedJSON["promotions"] as? JSON {
                return promotions
            } else {
                return nil
            }
        }
        set(value) {
            fetchedJSON["prmotions"] = value
        }
    }

    subscript(property: String) -> Any? {
        get {
            return fetchedJSON[property]

        }
        set(newValue) {
            fetchedJSON[property] = newValue
        }
    }
}

或者创建一个有限的 KVC(这也可以通过 Oliver Borchert 的另一个答案中所述的反射来完成):

class Singleton {

    var alpha : Any?
    var beta : Any?
    var delta : Any?

    subscript(property: String) -> Any? {
        get {
            switch property {
            case "alpha" : return self.alpha
            case "beta" : return self.beta
            case "delta" : return self.delta
            default : return nil
            }
        }
        set(newValue) {
            switch property {
            case "alpha" : self.alpha = newValue
            case "beta" : self.beta = newValue
            case "delta" : self.delta = newValue
            default : return
            }
        }
    }   
}

关于swift - 在 Swift 中通过下标访问单例属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34092394/

相关文章:

ios - swift Gmail API : Try to send message gives error -1001

ios - 如何在 Swift 中将值发送到父 View Controller

ios - PaintCode - 在路径上移动对象

java - 从另一个类访问的单例类

java - 如何修复 JVM 中的单例问题?

ios - 关闭多个 Controller

Objective-c 单例基类

string - 如何将 Int 转换为 String.CharacterView.Index

swift - 矩阵中不同列中的快速更改值更改了另一个

c++ - 数组下标错误的类型 'int[int]'无效