TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

SOLVED: How do I access a property of a nested struct?

Forums > SwiftUI

I am trying to access the property of a struct within a struct, and I'm sure I'm doing something wrong. E.g.: customers.address.address_line_1. I'm trying to do it this way because it's the model for a JSON response, and address is nested in the response.

struct arrayOfCustomers: Codable {
    var customers: [Customer]
}

struct Customer: Codable, Identifiable  {
    var id: String
    var created_at: String
    var updated_at: String
    var given_name, family_name, email_address, phone_number: String?

    struct Address: Codable {
      var address_line_1, locality, administrative_district_level_1, postalCode: String?
      var country: String?
  }
}

Example of the response:

{
  "customers": [
    {
      "id": "MJAG403GV96BX367R56N4FZJTG",
      "created_at": "2021-11-07T04:18:21.42Z",
      "updated_at": "2021-11-07T23:10:20Z",
      "given_name": "Test",
      "family_name": "Customer",
      "email_address": "email@email.com",
      "address": {
        "address_line_1": "123 Any St",
        "locality": "Somewhere",
        "administrative_district_level_1": "CA",
        "postal_code": "55555"
      },
      "phone_number": "+12025551234",
      "preferences": {
        "email_unsubscribed": false
      },
      "creation_source": "DIRECTORY",
      "segment_ids": [
        "MLPYEYRXNK0KW.REACHABLE"
      ],
      "version": 1
    }
  ]
}

3      

You are missing in struct Customer

var address: Address

As customers is an array you need customers[0].address.address_line_1

4      

Thank you! That did it.

3      

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.