1

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]]
1
  • Why is "boyOrGirl" a Bool? That's not really a "true/false" question. "Are you a boy or a girl?" "Yes."...? You could use an enum for various gender options instead. Commented Nov 13, 2014 at 21:56

2 Answers 2

5

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)]
Sign up to request clarification or add additional context in comments.

Comments

1

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)]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.