swift 展开要在ForEach中使用的可选@State数组

wkftcu5l  于 2023-08-02  发布在  Swift
关注(0)|答案(2)|浏览(103)

我试图打开一个可选的@State变量,以便在ForEach中使用,但我不确定我是否正确地这样做,它会抛出错误。有什么见解吗?

import SwiftUI

struct CommentView: View {
    
    @State private var commentsQuery: Comments?
    var postPublicId: String
    
    var body: some View {
        
        VStack {
          
            if let commentsQuery = Binding($commentsQuery) {
                ForEach(commentsQuery.comments, id: \.id) { comment in
                    CommentCellView(comment: comment)
                    
                }
            }
        }
         //.onAppear (Reach out to server for data)
    }
}

字符串
FYI这里是结构对象

struct Comments: Codable {
    var comments: [Comment]?
    var next: String?
}

struct Comment: Codable {
    let id: String
    let title: String
    let body: String
}


谢谢你,谢谢

to94eoyn

to94eoyn1#

我不明白你为什么要在这里装订。你可以像它是一个普通变量一样展开,这在视图构建器中是支持的:

if let commentsQuery {
    ForEach(commentsQuery.comments ...
}

字符串
或者,如果不需要额外的嵌套级别,则提供默认值:

ForEach(commentsQuery?.comments ?? [] ...


此外,使Comment符合Identifiable,那么您不需要指定ID。

7tofc5zh

7tofc5zh2#

我的建议是使@State属性成为非可选的,这样代码就更容易实现了

struct CommentView: View {
    @State private var commentsQuery: Comments
    var postPublicId: String

    var body: some View {
        VStack {
            ForEach($commentsQuery.comments, id: \.id) { $comment in
                CommentCellView(comment: $comment)
            }
        }
    }
}

字符串
然后在CommentCellView中使用@Binding,类似于

struct CommentCellView: View {
    @Binding var comment: Comment
    var body: some View {
        VStack {
            TextField("Title", text: $comment.title)
            TextField("Body", text: $comment.body)
        }
    }
}


我还对模型类型进行了一些更改,以使其能够工作

struct Comments: Codable {
    var comments: [Comment] = [] 
    var next: String?
}

struct Comment: Codable, Identifiable {
    let id: String
    var title: String
    var body: String
}

相关问题