0

If my REST API can send partial responses back (as specified here: https://developers.google.com/gmail/api/guides/performance), is it best to make all my properties in my Swift objects optional? Or is there an another pattern to handle this?

For example, my user object:

public struct User: Decodable {
    var id: Int
    var firstName: String
    var lastName: String
    var phoneNumber: String?
    var verified: Bool
}

In the DB, only phone number is optional, all the rest are required. Hence, only phone number in my swift object is marked as optional. However when it comes to the API responses, not all requests for user objects will contain all the required properties. For example, if I need to know which users are verified (GET /users?verified=true&fields=id), my response would just be a collection of user ids.

Does that mean that in Swift, I'd need to mark all properties except for id as optional?

Related question on SO: Should I use optional for properties of object models that will be parsed from JSON?

Prabhu
  • 12,995
  • 33
  • 127
  • 210
  • In my case, server will provide all information of users, and that would not be a problem if all properties are not optional. But if the use's information is over size, I prefer create a new struct like `UserForDisplay` which just include the necessary properties. – Klein Mioke May 02 '18 at 03:14

1 Answers1

0

If you are only getting Ids, you could create a different object to decode it:

public struct IdList: Decodable {
  var ids:[String]
}