首先沒有必要使用一個類,一個結構就足夠了。
與failable初始化期待一個JSON字符串和可變jsonRepresentation
struct Credentials {
var username = ""
var password = ""
init(username: String, password:String) {
self.username = username
self.password = password
}
init?(json : String) {
guard let data = json.data(using: .utf8),
let jsonDict = try? JSONSerialization.jsonObject(with: data, options: []) as? [String:String],
let username = jsonDict?["username"],
let password = jsonDict?["password"] else { return nil }
self.username = username
self.password = password
}
var jsonRepresentation : String {
let jsonDict = ["username" : username, "password" : password]
if let data = try? JSONSerialization.data(withJSONObject: jsonDict, options: []),
let jsonString = String(data:data, encoding:.utf8) {
return jsonString
} else { return "" }
}
}
請告訴我這個問題的簡單解決方案?只是爲他們制定方法?你可以用json初始化該類 – Tj3n
通常在Objective-C中,我們聲明(和代碼)' - (id)initWithJSONDict:(NSDictionary *)jsonDict'並且對於轉換,它依賴於(字符串表示,NSData之一,字典之一? – Larme