我想使用ObjectMapper在单例情况下解析Json字符串。示例代码:
class User: Mappable {
var username: String?
var signature: String?
//Singleton
static let shared = User()
private init() {}
//Mappable functions
required init?(map: Map) {}
func mapping(map: Map) {
username <- map["username"]
signature <- map["signature"]
}
//Update userInfo after network request
func getUserInfo() {
//Network things
...
//Example data
let data = [
"username": "Eason",
"signature": "I love U"
]
//Some thing like this to update userInfo
Mapper<User>().map(data)
}
}
那么,在单例情况下使用ObjectMapper的正确方法是什么?
答案 0 :(得分:1)
我更喜欢以下选项。
1)UserManager(单个):
Bet.Events["one"]
2)用户模型:
Bet.Events["one"] = Event{
Name: "first",
Runners: make(map[int]Runner),
}
3)RestClient
class UserManager: NSObject {
static let shared = UserManager()
var profile: UserProfile?
private override init() {}
func loadUserProfile(completion: @escaping () -> ()) {
RestClient.shared.getUserProfile() { [weak self] (profile, error) in
guard let `self` = self else { return }
self.profile = profile as? UserProfile
completion()
}
}
}