我認為這可能是我的移動 GitHub 查詢存盤庫搜索專案的最后一次推動,但我遇到了 3 個錯誤,我不知道如何處理。
代碼:
import SwiftUI
import Combine
struct Root: Codable {
let items: [Item]
enum CodingKeys: String, CodingKey {
case items
}
}
struct Item: Identifiable, Codable {
let id: Int
let urlCode: String
let fullName: String
enum CodingKeys: String, CodingKey {
case id
case urlCode = "url"
case fullName = "full_name"
}
}
private final class ContentViewState: ObservableObject {
@Published var isLoading = false
@Published var query = ""
@Published var stuff = [String]()
private var subscription: AnyCancellable?
func fetchRepos(query: String) {
isLoading = true
subscription = Just("test")
.delay(for: 2, scheduler: RunLoop.main)
.sink(receiveValue: {[weak self] (title: String) in
self?.isLoading = false
self?.stuff.append(title)
})
}
}
struct ContentView: View {
@StateObject private var state = ContentViewState()
@State private var items = [Item]()
var body: some View {
VStack {
if state.isLoading {
ProgressView()
} else {
HStack {
TextField("Enter search", text: $state.query)
Button("Search") {
state.fetchRepos(query: state.query)
}
}
List(items, id: \.id) { item in
VStack(alignment: .leading) {
Text(item.fullName).font(.headline)
Text(item.urlCode)
}
}.task {
await loadData()
}
}
}
}
func loadData() async {
guard let url = URL(string: "https://api.github.com/search/repositories?q=" state.query "&per_page=20") else
{
print("Invalid URL")
return
}
do {
let (data, _) = try await URLSession.shared.data(from: url)
if let decodedResponse = try? JSONDecoder().decode(Root.self, from: data) {
items = decodedResponse.items
}
} catch {
print("Invalid data ")
}
}
}
錯誤:“無法推斷通用引數'成功'”在線:
TextField("Enter search", text: $state.query)
“鍵路徑值型別' '無法轉換為背景關系型別' '”上線:
await loadData()
}
}
“在范圍內找不到'回應'”在線:
} catch {
print("Invalid data ")
}
}
}
請幫忙 :)
uj5u.com熱心網友回復:
答案是將代碼移動到另一個檔案,稍微改變它的結構,現在一切正常!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/411187.html
標籤:
上一篇:回傳首頁FastAPI
