我有一个简单的用户配置文件模型,它作为单个节点从 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'”?
如果我有一个数据循环,那么像下面这样循环就没有问题,但是我如何处理单个节点?
if let videos = videos {
self.videos = videos.map(VideoViewModel.init)
}
似乎您的 UserProfileService().getProfile 已经返回 UserProfile 类型,因此您可能需要
UserProfileService().getProfile { profile in
if let profile = profile {
self.profile = profile
}
}
和
@Published var profile : UserProfile?
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句