SwiftUI-如何在Swift中使用结果
如果我使用此代码,工作正常SwiftUI-如何在Swift中使用结果,swiftui,Swiftui,如果我使用此代码,工作正常 import Foundation enum NetworkError: Error { case badURL } func fetchUnreadCount(from urlString: String, completionHandler: @escaping (Result<Int, NetworkError>) -> Void) { guard let url = URL(string: urlString) else
import Foundation
enum NetworkError: Error {
case badURL }
func fetchUnreadCount(from urlString: String, completionHandler: @escaping (Result<Int, NetworkError>) -> Void) {
guard let url = URL(string: urlString) else {
completionHandler(.failure(.badURL))
return
}
// complicated networking code here
print("Fetching \(url.absoluteString)...")
completionHandler(.success(5)) }
fetchUnreadCount(from: "https://www.hackingwithswift.com") { result in
switch result {
case .success(let count):
print("\(count) unread messages.")
case .failure(let error):
print(error.localizedDescription)
} }
<代码>导入基础
枚举网络错误:错误{
case badURL}
func fetchUnderCount(来自urlString:String,completionHandler:@escaping(Result)->Void){
guard let url=url(字符串:urlString)else{
completionHandler(.failure(.badURL))
返回
}
//这里有复杂的网络代码
打印(“获取\(url.absoluteString)…”)
completionHandler(.success(5))}
FetchUnderCount(从:https://www.hackingwithswift.com“{”导致
切换结果{
成功案例(让我们计算):
打印(“\(计数)未读邮件。”)
案例。失败(let错误):
打印(错误。本地化描述)
} }
如果我使用与SwiftUI相同的代码,则不工作(请参见下面的屏幕截图)
如何消除错误?
body
必须返回一个视图,所以只需添加return EmptyView()
或在fetchUnreadCount之后显示的任何视图
struct ContentView: View {
var body: some View {
fetchUnreadCount(from: "https://www.hackingwithswift.com") { result in
switch result {
case .success(let count):
print("\(count) unread messages.")
case .failure(let error):
print(error.localizedDescription)
} }
return EmptyView()
}
}
不管怎样,你不应该在视图中获取数据,这项工作应该在模型中完成body
必须返回一个视图,所以只需添加return EmptyView()
或在fetchunedcount
之后显示的任何视图,你能给我一个上面代码中的示例吗?谢谢