Heinevolder
Heinevolder

Reputation: 338

Creating array with struct in swift

So. I have tried to create a person with struct in Swift and i'm wondering how to create an array using an instance of my struct.

Can anybody tell me how to do this?

struct Person{
     var name: String
     var boyOrGirl: Bool

     init(names: String, bOg: Bool){
        self.name = names
        self.boyOrGirl = bOg
    }
}
var personArray: Person = [["Heine",true], ["Magnus",true]]

Upvotes: 1

Views: 7800

Answers (2)

Antonio
Antonio

Reputation: 72750

An instance of Person is created as:

Person(names: "Heine", bOg: true)

There are 2 errors instead in your code:

var personArray: Person = [["Heine",true], ["Magnus",true]]
                 ^^^^^^    ^^^^^^^^^^^^^^
  1. personArray should be an array, whereas you declared it as Person
  2. what you are doing here is adding an array containing a string and a boolean

The correct syntax is:

var personArray: [Person] = [Person(names: "Heine", bOg: true), Person(names: "Magnus",bOg: true)]

Note that the variable type [Person] can be omitted because the compiler can infer the type from the value assigned to the personArray variable:

var personArray = [Person(names: "Heine", bOg: true), Person(names: "Magnus",bOg: true)]

Upvotes: 5

David Berry
David Berry

Reputation: 41226

You'd use:

var personArray: [Person] = [Person(name:"Heine",bOg:true), Person(name:"Magnus",bOg:true)]

or, since the array type can be inferred, even:

var personArray = [Person(name:"Heine",bOg:true), Person(name:"Magnus",bOg:true)]

Upvotes: 1

Related Questions