我正在尝试设置一个名为 allCountries 的已发布变量。在我的 DispatchQueue 中,它正在被设置并且实际上正在将正确的信息打印到控制台。在我的内容视图中,数组中没有任何内容。在内容视图的 init 函数中,我调用将获取数据并设置变量的函数,但当我打印到控制台时,变量为空。有人可以告诉我我做错了什么吗?
这是我获取数据的地方
class GetCountries: ObservableObject {
@Published var allCountries = [Countries]()
func getAllPosts() {
guard let url = URL(string: "apiURL")
else {
fatalError("URL does not work!")
}
URLSession.shared.dataTask(with: url) { data, _, _ in
do {
if let data = data {
let posts = try JSONDecoder().decode([Countries].self, from: data)
DispatchQueue.main.async {
self.allCountries = posts
print(self.allCountries)
}
} else {
DispatchQueue.main.async {
print("didn't work")
}
}
}
catch {
DispatchQueue.main.async {
print(error.localizedDescription)
}
}
}.resume() …Run Code Online (Sandbox Code Playgroud) 我正在尝试在 swiftui 中创建网格视图,但它不适合我。有人可以告诉我我做错了什么吗?我尝试使用 ac 风格的 for 循环,我可以在其中设置变量并递增它,但是当我这样做时 swiftui 会抛出错误。
struct ProductSubCat: View {
@State var productCategory = String()
@State var number = Int()
@ObservedObject var allData = WebserviceGetDataSolutions()
@State var theCount = 0
var body: some View {
ScrollView {
Spacer()
ForEach(0 ..< self.allData.posts[self.number].productLines.count / 2, id: \.self) {row in
HStack {
ForEach(0..<2) {cell in
NavigationLink(destination: ProductDetails())
{
Text(self.allData.posts[self.number].productLines[row].system)
Image("stonclad")
.resizable()
.aspectRatio(contentMode: .fit)
}.buttonStyle(PlainButtonStyle())
}
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)