0

我有带有自定义数据的 JSON 文件。目标PostCard()是在中使用这些数据ForEach(){}。但是我尝试在里面使用evetytime user,我在VStack中收到这个错误无法推断复杂的闭包返回类型;添加显式类型以消除歧义

我的 JSON 转换器函数如下所示:

let userResponse: [UserResponse] = load("users.json")



func load<T: Decodable>(_ filename: String, as type: T.Type = T.self) -> T {
    let data: Data

    guard let file = Bundle.main.url(forResource: filename, withExtension: nil)
        else {
            fatalError("Couldn't find \(filename) in main bundle.")
    }

    do {
        data = try Data(contentsOf: file)
    } catch {
        fatalError("Couldn't load \(filename) from main bundle:\n\(error)")
    }

    do {
        let decoder = JSONDecoder()
        return try decoder.decode(T.self, from: data)
    } catch {
        fatalError("Couldn't parse \(filename) as \(T.self):\n\(error)")
    }
}

自定义数据类型:

struct UserResponse: Hashable, Codable, Identifiable {
   public var id: Int
   public var username: String
   public var avatar: String
   public var postOne: String
   public var postTwo: String
   public var postThree: String
   public var postFour: String
   public var story: String
   public var likes: Int
   public var commentNumber: Int
   public var location: String
   public var comment: String
   public var name: String
   public var followers: Int
   public var following: Int
   public var postNumbers: Int
   public var bio: String
   public var locationPic: String
}

我在子视图中初始化它:

var user : UserResponse
ZStack{
   VStack{
      ForEach(userResponse){user in
         HStack(alignment: .center, spacing: 5){             
            PostCard(user: user)
               .padding(EdgeInsets(top: 0, leading: 5, bottom: 0, trailing: 0))

            PostCard(user: user)
               .padding(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 5))

         }.shadow(color: Color("greySec"), radius: 3, x: 0, y: 0)
      }
   }.navigationBarTitle(Text(""), displayMode: .inline)
      .navigationBarHidden(true)
}

我的PostCard结构如下所示:

var user : UserResponse
VStack(spacing: 10){
   HStack(spacing: 5){
      VStack(spacing: 10){
         Image(user.postOne)
            .resizable().frame(height: 290)

         HStack{
            Text(user.comment)
               .font(.system(size: 12, weight: .medium))
               .padding(EdgeInsets(top: 0, leading: 5, bottom: 0, trailing: 5))
         }
      }
      .background(Color("whiteAndBlack"))
      .cornerRadius(5)
      .foregroundColor(.black)
   }
}

问题:有没有人知道如何在里面使用 JSON 数据ForEach(){}?我的目标是使用每个 PostCard 的各种 JSON 数据创建此视图。

4

0 回答 0