-
Notifications
You must be signed in to change notification settings - Fork 653
支持泛型
xuyecan edited this page Sep 12, 2017
·
2 revisions
有一种常见场景:服务端不同接口返回经过统一包装的数据结构,在包装的code
/message
字段中存放请求本身的信息,然后有一个data
字段,根据接口不同,存放不同的业务数据,如:
class Response {
var statusCode: Int?
var message: String?
var data: Any?
}
这种情况,我们可以用泛型来支持,并很方便地配合HandyJSON
工作。
这里,将Response
定义为:
class Response<T: HandyJSON>: HandyJSON {
var statusCode: Int?
var message: String?
var data: T?
required init() {}
}
然后定义具体的业务数据结构:
class SomeBizData: HandyJSON {
var id: Int?
var name: String?
required init() {}
}
class AnotherBizData: HandyJSON {
var id: Int?
var value: Double?
required init() {}
}
就可以在不同的业务接口中使用了:
func mockRpc1() {
let mockRespStr = "{\"statusCode\":200,\"data\":{\"id\":12345,\"name\":\"some biz\"},\"message\":\"success\"}"
if let response = Response<SomeBizData>.deserialize(from: mockRespStr) {
print(response.data?.name ?? "")
}
}
func mockRpc2() {
let mockRespStr = "{\"statusCode\":200,\"data\":{\"id\":54321,\"value\":1.2345},\"message\":\"success\"}"
if let response = Response<AnotherBizData>.deserialize(from: mockRespStr) {
print(response.data?.value ?? 0)
}
}