所以我有一个用户 JSON 结构,如下所示:
- results: {
meta: {}
users: []
},
- status:
我想让用户这样User
我实现的获取 JSON 的模型如下:
struct Response: Decodable {
let results: Result
let status: Int
}
struct Result: Decodable {
let meta: Meta
let users: [User]
}
struct Meta: Decodable {
let total_data: Int
let total_page: Int
}
struct User: Decodable {
let avatar_url: String
let created_at: String
let updated_at: String
let email: String
let id: Int
let name: String
let username: String
}
它正在工作,但是当我有另一个结构相似的 JSON 时,可以这样说
- results: {
meta: {}
rooms: []
},
- status:
当我创建时Room
模型,与另一个struct Response
在它上面,会因为重复声明而导致错误。
Swift 中可以重用 struct 吗?或者有什么方便的方法可以做到这一点吗?
Thanks
您可以使用泛型。
struct Response<T: Decodable>: Decodable {
let results: Result<T>
let status: Int
}
struct Result<T: Decodable>: Decodable {
let meta: Meta
let objects: [T]
}
struct Meta: Decodable {
let total_data: Int
let total_page: Int
}
struct User: Decodable {
let avatar_url: String
let created_at: String
let updated_at: String
let email: String
let id: Int
let name: String
let username: String
}
let userResponse: Response<User>?
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)