Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - Make Arrays Of Structs

Tags:

swift

swift3

I am trying to add structs to an array. I know it's possible. I have seen it in another post on the site. But I am wondering if there is any way to add structs to an array without creating variables.

For example:

struct Person {
    var name: String
    var surname: String
    var phone: Int
    var isCustomer: Bool
}

var contacts: [Person] = []

var person1: Person = Person(name: "Jack", surname: "Johnson", phone: 2, isCustomer: false) 
var person2: Person = Person(name: "alex", surname: "a", phone: 3, isCustomer: false)

contacts.append(person1)
contacts.append(person2)

for contact in contacts {
    print("\(contact.name)")
}

In this code we use person1 and person2 to create a "contact". But if you have to create hundreds of contacts it is annoying to setup up all these variables.

What I tried is this:

struct Person {
    var name: String
    var surname: String
    var phone: Int
    var isCustomer: Bool
}

var contacts: [Person] = []

Person(name: "Jack", surname: "Johnson", phone: 2, isCustomer: false)

contacts.append(Person) // Here I get this error: "Cannot convert value of type '(Person).Type' (aka 'Person.Type') to expected argument type 'Person'

Is there any way to add structs to an array without creating variables?

like image 776
Alex Karapanos Avatar asked Nov 11 '16 18:11

Alex Karapanos


1 Answers

It is giving you an error because you are trying to insert the type Person and not an instance. If you want to add a person to contacts without binding it to a variable just do this:

contacts.append(Person(name: "Jack", surname: "Johnson", phone: 2, isCustomer: false))
like image 162
Adam Van Prooyen Avatar answered Oct 26 '22 06:10

Adam Van Prooyen