Alexey K
Alexey K

Reputation: 6723

Dynamically create objects from function

Im sorry in advance if my question is too silly, Im new to OOP and programming generally, but i need to figure out a way to create objects dynamically. For example I have a class with init like this

   class User {
     var name: String = ""
     var age: Int = 0

   init (name: String, age: Int) {
     self.name = name
     self.age = age
     }
   }

I can create new object by using

var newUser = User(name: "Joe", age: 21)

but i do it manually by hands in code.

How can I automate the process so every time I need to create an object, I pass name, age and object creates automatically with assigning to new variable without mentioning the variable name (for example, there is pattern to for creation a variable, so it does user1, user2, user3 and so on) ? Do I Have to create a specific builder function that creates instances of user?

Upvotes: 0

Views: 357

Answers (2)

Cole
Cole

Reputation: 2646

If you want to create a large list of users for JSON or something without having to assign a bunch of variable names by hand, I would use a Dictionary and dynamically create the key and value. So a function would look like this

var dynamicallyAssignedName: String?
var dynamicallyAssignedAge: Int?

var users: Dictionary<String, User>?
func newUser(name: String, age: Int) {

    var createUser = User(name: dynamicallyAssignedName, age: dynamicallyAssignedAge)

    users[dynamicallyAssignedName] = createUser
}

Then you can upload the dictionary fairly easily.

Upvotes: 1

matt
matt

Reputation: 535566

You might mean something like this:

let arr = [("Matt", 61), ("Alexey", 123)]
let arr2 = arr.map {User(name:$0.0, age:$0.1)}

Upvotes: 0

Related Questions