我有一个单例类:
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/