-
Notifications
You must be signed in to change notification settings - Fork 652
基本类型
xuyecan edited this page Sep 11, 2017
·
3 revisions
要支持从JSON串反序列化,Model定义时要声明服从HandyJSON
协议。
服从HandyJSON
协议,需要实现一个空的init
方法。
class BasicTypes: HandyJSON {
var int: Int = 2
var doubleOptional: Double?
var stringImplicitlyUnwrapped: String!
required init() {}
}
let jsonString = "{\"doubleOptional\":1.1,\"stringImplicitlyUnwrapped\":\"hello\",\"int\":1}"
if let object = BasicTypes.deserialize(from: jsonString) {
// …
}
对于声明为struct
的Model,由于struct
默认提供了空的init
方法,所以不需要额外声明。
struct BasicTypes: HandyJSON {
var int: Int = 2
var doubleOptional: Double?
var stringImplicitlyUnwrapped: String!
}
let jsonString = "{\"doubleOptional\":1.1,\"stringImplicitlyUnwrapped\":\"hello\",\"int\":1}"
if let object = BasicTypes.deserialize(from: jsonString) {
// …
}