简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM