【发布时间】:2020-07-21 07:55:33
【问题描述】:
我有一个简单的用户配置文件模型,它作为单个节点从 JSON API 返回。
(模型)UserProfile.swift
struct UserProfile: Codable, Identifiable {
let id: Int
var name: String
var profile: String
var image: String?
var status: String
var timezone: String
}
(服务)UserProfileService.swift
class UserProfileService {
func getProfile(completion: @escaping(UserProfile?) -> ()) {
guard let url = URL(string: "https://myapi.com/profile") else {
completion(nil)
return
}
var request = URLRequest(url: url)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.httpMethod = "GET"
URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
DispatchQueue.main.async {
completion(nil)
}
return
}
do {
let profile = try JSONDecoder().decode(UserProfile.self, from: data)
DispatchQueue.main.async {
completion(profile)
}
} catch {
print("ERROR: ", error)
}
}.resume()
}
}
(查看模型)UserProfileViewModel.swift
class UserProfileRequestViewModel: ObservableObject {
@Published var profile = UserProfile.self
init() {
fetchProfile()
}
func fetchProfile() {
UserProfileService().getProfile { profile in
if let profile = profile {
self.profile = UserProfileViewModel.init(profile: profile)
}
}
}
}
class UserProfileViewModel {
var profile: UserProfile
init(profile: UserProfile) {
self.profile = profile
}
var id: Int {
return self.profile.id
}
}
有人可以告诉我需要在上面输入什么self.profile = UserProfileViewModel.init(profile: profile),因为这会导致错误“无法将'UserProfileViewModel'类型的值分配给'UserProfile.Type'”? p>
如果我有一个数据循环,那么像下面这样循环不会有问题,但是如何处理单个节点?
if let videos = videos {
self.videos = videos.map(VideoViewModel.init)
}
【问题讨论】: