2017-04-11 48 views
0

我對Swift非常陌生,我無法弄清楚這一點。我需要計算一個結構內創建的實例的數量。由於我創建了3個實例,我怎樣才能讓程序告訴我有三個實例?我在最後嘗試了exNames.count,但那不起作用......謝謝!在swift中統計結構內的實例數

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 
+5

'exNames'是一個空數組。 - 看看http://stackoverflow.com/questions/38021844/count-number-of-instances-of-a-class-swift。 –

回答

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它提供了一個deinitializer deinit {}

請注意,靜態計數器的「正確」用例非常有限。不同的錘子很可能會更好地解決您實際嘗試解決的問題。

順便說一句,你真的不應該使用Character表示sex,如斯威夫特Character非常密切相關的字符串,所以它們是建立和優化的詞彙,而不是用於標記。它也爲很多潛在的錯誤打開了大門,因爲Swift無法驗證有效輸入(如果有人不小心通過sex"@"?)而是使用內置的Bool類型或自定義如果您需要更多功能,請致電enum

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