1

I am consuming an API in Swift 4 using Alamofire. I am using structs to create Models of the data I wish to consume within that response and am confirming to Decodable.

My response looks like so...

    {  
       "pagination":{  
          "per_page":50,
          "items":3909,
          "page":1,
          "urls":{  
             "last":"https://api.discogs.com/database/search?q=ed+rush&per_page=50&secret=foo&page=79&key=bar",
             "next":"https://api.discogs.com/database/search?q=ed+rush&per_page=50&secret=foo&page=2&key=bar"
          },
          "pages":79
       },
       "results": []
    }

My models looks as follows...

struct SearchResults: Decodable {
    let pagination: SearchPagination
    let results: [SearchResult]
}

struct SearchResult: Decodable {
    let type: String
}

struct SearchPagination: Decodable {
    let per_page: Int
    let items: Int
    let page: Int
    let pages: Int
}

What I am trying to understand is how I would model pagination as urls is a nested object itself. Do I create a struct just for urls or am I missing something obvious here?

Perhaps a struct is not the best approach? I am coming from a JS background and structs feel very much like an interface in TypeScript however I am aware I may be missing something here.

1
  • 1
    You should create a struct for urls. Commented May 14, 2018 at 6:35

1 Answer 1

2

The "rule" of Decodable is that any dictionary {} becomes a struct / class and each key becomes a property.

struct SearchPagination: Decodable {
    let per_page: Int
    let items: Int
    let page: Int
    let pages: Int
    let urls: URLData
}

struct URLData: Decodable {
    let last, next : URL
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.