我对Swift很新,但我无法解决这个问题。我需要计算结构中创建的实例数。由于我创建了3个实例,我怎样才能让程序告诉我有三个实例?我最后尝试了exNames.count,但那不起作用......谢谢!
struct People {
let name: String
var age: Int
let sex: Character
}
var heather = People(name: "Heather", age: 32, sex: "F")
var peter = People(name: "Peter", age: 34, sex: "M")
var scott = People(name: "Scott", age: 27, sex: "M")
let exNames = [People]()
exNames.count
答案 0 :(得分:2)
您想在People
结构上使用静态变量。但是,这确实需要覆盖默认初始值设定项。
struct People
{
static var instances = 0
let name:String
var age:Int
let sex:Character
init(name:String, age:Int, sex:Character)
{
self.name = name
self.age = age
self.sex = sex
People.instances += 1
}
}
var heather = People(name: "Heather", age: 32, sex: "F")
var peter = People(name: "Peter", age: 34, sex: "M")
var scott = People(name: "Scott", age: 27, sex: "M")
let exNames = [People]()
/* exNames.count only gives the number of People that are
contained in this particular array, which is zero. */
print(People.instances) // 3
如果您希望在struct
超出范围时减少计数,则需要升级到提供取消初始化class
的{{1}}
请注意,静态计数器的“正确”用例非常有限。你实际上试图解决的问题很可能会被另一把锤子更好地服务。
顺便说一句,你真的不应该使用deinit {}
来表示Character
,因为Swift中的sex
与字符串紧密相关,因此它们是为了构建和优化的词汇目的,而不是标记。它还为很多潜在的错误打开了大门,因为Swift也无法验证有效输入(如果有人意外传递了Character
sex
的值,该怎么办?)相反,请使用如果您需要更多功能,则内置"@"
类型或自定义Bool
。
答案 1 :(得分:2)
在这种情况下,您似乎想创建一组人:
struct People {
let name: String
var age: Int
let sex: Character
}
var heather = People(name: "Heather", age: 32, sex: "F")
var peter = People(name: "Peter", age: 34, sex: "M")
var scott = People(name: "Scott", age: 27, sex: "M")
//This should be a var, because you are going to modify it
var exNames = [People]()
exNames.append(heather)
exNames.append(peter)
exNames.append(scott)
exNames.count