初始化中的Swift动态属性

时间:2015-08-26 05:10:13

标签: swift class initialization swift-playground

我正在使用Swift 2.0在Xcode 7 beta 5中工作。我想我的结构初始化有问题。

//called when key is pressed in textbox
  $("#quantity").keydown(function (e) {
     //if the letter is not digit then display error and don't type anything
     if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
        //display error message
        $("#errmsg").html("Digits Only").show().fadeOut("slow");
               return false;
    }
   });

我遇到了麻烦。

enum Resource {
    case gold
    case elixer
    case darkElixer
}

class Avatar {
    let cost, health, damage, space: Int
    let lifeSpan: Double
    let costType: Resource


    init(damage: Int, health: Int, cost: Int, costType: Resource, space: Int){
        self.damage = damage
        self.health = health
        self.cost = cost
        self.costType = costType
        self.space = space
        self.lifeSpan = Double(damage / health)
}

我只想弄清楚如何在初始化期间动态设置属性。

1 个答案:

答案 0 :(得分:0)

经过一些研究后,我找到了答案。

var lifeSpan: Double {
    get {
        return  Double(health) / Double(damage)
    }

}