Skip to content
Ryan Bush edited this page Apr 24, 2017 · 1 revision

Entities are data objects that we use throughout the application. They can be used anywhere, and are typically created by Services. They can be passed around any of the VIPER layers and used as needed.

Lets take a look a typical User entity

//User.swift
class User {
    // Identifier
    let userId: Int

    // Instance Variables
    let gender: String?
    let password: String?
    let username: String?
    
    // Initializers
    init(withUserId newUserId: Int) {
         userId = newUserId 
    }
    
    init?(fromJson json: [String: AnyObject]) {
        let json = JSON(jsonDictionary)
        let identifier = json["userId"].int

        guard identifier != nil else {
            return nil
        }

        self.init(withUserId: identifier)

        gender = json["gender"].string
        password = json["password"].string
        username = json["username"].string
    }
}

Here, we have a basic User object. In the init(withJson:) method we use SwiftyJSON to easily parse the JSON's values into the objects instance variables.