xcode 快速创建带有结构的数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26918978/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating array with struct in swift
提问by Heinevolder
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.
所以。我试图在 Swift 中创建一个带有 struct 的人,我想知道如何使用我的 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]]
回答by Antonio
An instance of Person
is created as:
的实例Person
创建为:
Person(names: "Heine", bOg: true)
There are 2 errors instead in your code:
您的代码中有 2 个错误:
var personArray: Person = [["Heine",true], ["Magnus",true]]
^^^^^^ ^^^^^^^^^^^^^^
personArray
should be an array, whereas you declared it asPerson
- what you are doing here is adding an array containing a string and a boolean
personArray
应该是一个数组,而您将其声明为Person
- 你在这里做的是添加一个包含字符串和布尔值的数组
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:
请注意,变量类型[Person]
可以省略,因为编译器可以从分配给personArray
变量的值推断类型:
var personArray = [Person(names: "Heine", bOg: true), Person(names: "Magnus",bOg: true)]
回答by David Berry
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)]