'Newbie SwiftUI Nested array

Please help me display my model data from api

I have a nested json data response and Have a swiftui model as below

****************************MyData model

struct MyData: Codable {
   let data: [Account]
}

// MARK: - Datum
struct Account: Codable {
    let id, username, password: String
}

my previous model was just the array but I adjusted for Nest. I read data and end up with read success from api below


` success(SwiftClient.MyData(data: [SwiftClient.Account(id: "1", username: "ooo111", password: "$2a$10$tyFnx6.7yR/MY3oQHDlySOoooG9RIpusOEIGmDCRkOI9ZXzV3rkpy"), SwiftClient.Account(id: "2", username: "oo222", password: "$2a$10$3iR3SdEjkVZ5w7/lgTdZwOvooohqd1L0jDt30k/nmSt0h47VyLfe")])) ********************** ```

however when I want to use my model to present data it fails

My viewmodel is below


` struct AccountViewModel {

let account: MyData




var id: String {
 //   return account.name
    return account.data.first!.id
}
var username: String {
    //return account.name
    return account.data.first!.username

}
var password: String {
    //return account.balance
    return account.data.first!.password
}

} ```


When I call it in below it runs but is empty array



\\\\and in my function call to get Accounts
case .success(let accounts):
                    DispatchQueue.main.async {
                      
                   self.accounts = accounts.data.map(AccountViewModel.init)
                     
                    } ```

***********

self.accounts = accounts.data.map... - fails with Value of type '[AccountViewModel]' has no member 'data'


what's the best way to unwrap my nest and display accounts 

Thanks In advance for help


Solution 1:[1]

I was using my struct outer nest when reading data . I just had to change they mydata back to account ion my model and it worked.

struct AccountViewModel {
    //let account: MyData
    let account: Account


    var id: String {
        return account.id
    }

    var username: String {
        return account.username
    }

    var password: String {
        return account.password
    } 
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Cedan Misquith