我有一个结构,并在很多类中使用它。我想有一种方法来计算每个类中初始化的结构数(比如array.count)我找不到任何内容。
struct measuredBMInfo {
var level: Int
var message: String
init(level: Int, message: String) {
self.level = level
self.message = message
}
}
我使用如下结构:
// setup pain
let painInfo0 = measuredPainInfo(level: 0, message: "No Pain")
let painInfo1 = measuredPainInfo(level: 1, message: "Mild pain can be ignored")
let painInfo2 = measuredPainInfo(level: 2, message: "Moderate pain that interferes with tasks")
let painInfo3 = measuredPainInfo(level: 3, message: "Moderate pain interferes with concentration")
let painInfo4 = measuredPainInfo(level: 4, message: "Severe pain interferes with basic tasks")
let painInfo5 = measuredPainInfo(level: 5, message: "Worst possible pain bedrest required")
在这种情况下,我想要计算一次measuredPainInfo。
答案 0 :(得分:1)
您可以定义一个存储结构的数组:
var structArray:[measuredBMInfo] = []
override func viewDidLoad() {
super.viewDidLoad()
setPainInfo(0, message: "dfsa")
setPainInfo(1, message: "dsger")
setPainInfo(2, message: "kh sdfujo")
setPainInfo(3, message: "sdfasfd")
print(getStructCount())
}
func setPainInfo(level:Int, message: String){
let painInfo = measuredBMInfo(level: level, message: message)
structArray.append(painInfo)
}
使用以下方法获取结构数:
func getStructCount()->Int{
return structArray.count
}