1

In my project I can't access the "Floor" to be used in for each loop. I need to count floors of a bulding in the loop.

// MARK: - UcmData
struct UcmData: Codable {
    let buildings: [Building]
}

// MARK: - Building
struct Building: Codable {
    let id: Int
    let title, subtitle, info, image: String
    let floor: [Floor]
}

// MARK: - Floor
struct Floor: Codable {
    let number: Int
    let title, subtitle, image: String
}
import SwiftUI
import Foundation

struct NamJHerduView: View {
    let ucmData = Bundle.main.decode(UcmData.self, from: "ucm_data.json")

    var body: some View {
        ScrollView {
            VStack {
                ForEach(0 ..< ucmData.) //here i need to count floors and use maybe where clause to filter just floors from a special building
redearz
  • 135
  • 1
  • 9

2 Answers2

0

I think you may want to organize your data so that it is nested like this:

// MARK: - UcmData
struct UcmData: Codable {
    let buildings: [Building]

    // MARK: - Building
    struct Building: Codable {
        let id: Int
        let title, subtitle, info, image: String
        let floor: [Floor]

        // MARK: - Floor
        struct Floor: Codable {
            let number: Int
            let title, subtitle, image: String
        }
    }
}

Then each building will have a floor array.

user212514
  • 3,110
  • 1
  • 15
  • 11
0

Add Identifiable conformance

struct Building: Codable, Identifiable {

Now you can loop through buildings

ForEach(ucmData.buildings) { building in
  Text("Number of floors in \(building.title): \(building.floors.count)")
}

If you also need to access the index in the loop, see this answer: How do you use .enumerated() with ForEach in SwiftUI?

Gil Birman
  • 35,242
  • 14
  • 75
  • 119
  • Yes this is looping trough the building, I have that alredy, but I can't make it loop trough floors of a building selected for example in condition based on buildings id – redearz Jan 06 '20 at 16:30
  • Same concept, make it conform to `Identifiable` and loop through it. – Gil Birman Jan 06 '20 at 18:03
  • I made Identifiabale Floor like this `struct Floor: Codable, Identifiable { let id, number: Int` with the `id` parameter, but still error occurs at the end of VStack from my first post at the top that "the compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions" – redearz Jan 06 '20 at 19:40