arrays - 尝试从 SwiftUI View 中的嵌套数组调用

标签 arrays json swift model swiftui

所以我有一个模型 [UserModel],其中包含嵌套数组 [CityModel],并且位于 [TownModel] 中。我很确定模型设置正确,但我认为我在尝试引用嵌套数组时语法错误。

这是我的 UserModel.swift:

import SwiftUI

struct UserModel: Codable, Identifiable {
    let id: Int
    let firstName: String
    let lastName: String
    let cities: [CityModel]

    enum CodingKeys: String, CodingKey {
        case id
        case firstName = "first_name"
        case lastName = "last_name"
        case cities
    }
}

struct CityModel: Codable {
    let name: String
    let towns: [TownModel]
}

struct TownModel: Codable {
    let name: String
}

问题出在我的 CityRow.swift 中,我只想在其中显示一个城市的名称(这样我就可以在 CityList 中调用它并显示用户下的所有城市)。

struct CityRow: View {
    var city: [UserModel.CityModel]

    var body: some View {
        VStack(alignment: .leading) {
            Text(city.name)
                .font(.headline)
        }
    }
}

struct CityRow_Previews: PreviewProvider {
    static var previews: some View {
        CityRow(city: userData[0])
    }
}

但在尝试写出我的“城市”变量时出现此错误。

'CityModel' is not a member type of 'UserModel'

我确定我的“var city: [UserModel.CityModel]”语法不正确,但不知道该怎么做?

最佳答案

您的 CityRow 需要一个城市才能调用它的名字。 CityModel 不是 UserModel 的成员,但 cities 是。 我不知道您的应用程序或您想要实现的目标,但是例如在列表中,您想要显示数组中的每个城市。 您的 CityRow 需要 var city: CityModel 作为构造函数。它可能看起来像这样(同样,我不知道您要实现什么,更多信息/代码会有所帮助!)。

这是你的城市行

struct CityRow: View {
    var city: CityModel

    var body: some View {
        VStack(alignment: .leading) {
            Text(city.name)
                .font(.headline)
        }
    }
}

这是您可以在列表或其他内容中使用的 ForEach 循环

ForEach(user.cities) {city in
    CityRow(city: city)
}

如果您可以使用更多代码来编辑您的问题,例如显示所有 CityRow 的 View ,那将会很有帮助!

关于arrays - 尝试从 SwiftUI View 中的嵌套数组调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58616977/

相关文章:

python - 读取/解析大量 JSON.gz 文件的优化技巧

ios - header 未显示在 UICollectionView 中,甚至已经在 UICollectionViewFlowLayout 中以编程方式注册

ios - 在 Swift 中使用 Unicode 代码点

java - 用java将值输入到二维数组中

php - 正确显示关联数组的结果 Laravel/PHP

javascript - 根据条件求和列制表符

javascript - 使用 $.grep() 基于自定义过滤器过滤列表

c# - JSON 响应自定义 .NET Core Web API

ios - 过渡前暂停场景并执行过渡

c++ - 如何借助指针按数组元素的余弦对数组进行升序排序?