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?
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With