I read somewhere that it was best practice to use structs when passing around model data using Swift.
I have been doing so but I have been wondering whether there is anything that I can do in regards to the creation of large (and growing) user data objects like this:
struct UserAccount {
var id: String?
let authId: String
let emailAddress: String
let mobilePhoneNumber: String
let firstName: String
let lastName: String
let countryCode: String
let homepageUrl: String
let tagline: String
let pictureUrl: String
let accountState: AccountState = .NoAccount
// ...
}
This is more or less what I use when I create a user account, but later on it feels cumbersome and wrong to have to instantiate gigantic objects in code. I am parsing JSON responses using json-swift but then having to instantiate the models separately, like so:
let id = jsonData["id"].string!
let authId = jsonData["authId"].string!
let emailAddress = jsonData["emailAddress"].string!
let mobilePhoneNumber = jsonData["mobilePhoneNumber"].string!
let firstName = jsonData["firstName"].string!
let lastName = jsonData["lastName"].string!
let countryCode = jsonData["countryCode"].string!
let homepageUrl = jsonData["homepageUrl"].string!
let tagline = jsonData["tagline"].string!
let pictureUrl = jsonData["pictureUrl"].string!
let accountState = convertAccountStateStringToEnum(jsonData["accountState"].string!)
let userAccount = UserAccount(
id: id,
authId: authId,
emailAddress: emailAddress,
mobilePhoneNumber: mobilePhoneNumber,
firstName: firstName,
lastName: lastName,
countryCode: countryCode,
homePageUrl: homepageUrl,
tagline: tagline,
pictureUrl: pictureUrl,
accountState: accountState
)
It might seem absurd that above I've instantiated the variables before I instantiate the struct, but the reason I did so is that when the IDE gives me type coercion errors from within a struct it is very difficult to understand what is wrong, and so this allows me to troubleshoot it quicker when I am making model changes. Any thoughts around this?
My Question:
Later on that user object is likely to contain a lot more data on the server side and instantiating use models with 50+ lines seems like a bad idea, therefore:
- Are there solutions to create structs in some simpler way? Does the pattern have a name?
- Should I be creating User models that are related to specific tasks? For example, a UserAccount model to GET or PUT a profile might be different from the one used to authenticate, get the user settings or list the most popular accounts on my service.
- Do people just leave it as it is and define mappers so that there is no redundancy? If so - what's a good example of this?
Thanks.