訪問一個Singleton財產標我有一個Singleton類:斯威夫特
class Session {
static let sharedInstance = Session()
private init() {}
// app properties
var token: String!
var promotions: JSON!
}
在網絡類我有我火了使用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上設置響應。我已經嘗試實現對辛格爾頓標無濟於事:
subscript(property: Any) -> Any {
get {
return Session.sharedInstance[property]
}
set(newValue) {
Session.sharedInstance[property] = newValue
}
}
我也試圖通過放棄符合下標來NSObject
和使用KVC
然而這也沒有工作&而且我失去了所有類型安全。
任何幫助或建議非常感謝。 在此先感謝。
爲什麼你需要下標?我猜,因爲你有更多的屬性,如「促銷」? –
也不需要做:'Session.sharedInstance [property] = newValue'只需使用:'self。[property] = newValue'然後你就可以清楚的知道你正在創建一個遞歸下標。 –