Bright Future Bright Future - 3 months ago 8
Swift Question

How to modify instance value without using a function?

I have a class:

class WeaponItems {

var name: String
var index: Int
var price: Int
var weaponPower: Int = 0
var attackSpeed: Double = 0
var criticalChance: Double = 0
var criticalDamage: Double = 0

init(name: String, index: Int, price: Int){
self.name = name
self.index = index
self.price = price
}

var weaponBlade = WeaponItems(name: "Weapon Blade", index: 0, price: 300)
weaponBlade.weaponPower = 15
// Error: expected declaration

var swiftShooter = WeaponItems(name: "Swift Shooter", index: 1, price: 300)
swiftShooter.attackSpeed = 0.2
// Error: expected declaration

var minionsFoot = WeaponItems(name: "Minions Foot", index: 3, price: 300)
minionsFoot.criticalChance = 0.1
minionsFoot.criticalDamage = 0.1
// Error: expected declaration

}


I need to set
weaponPower
attackSpeed
... for each item, I got an error doing it this way.

I found answers saying you have to use a function to modify instances' values, but I feel that makes the code complicated, how do I set the value of it otherwise?

The concern of using a function is it'll separate the instance-creating and value-setting process, making the code harder to maintain.

Answer

If you wish to have default property values, which you would also like the opportunity to customise when creating an instance, then I would recommend using default parameter values in your initialiser. This will allow you to create a new instance of your WeaponItems class with the actual property values known at initialisation, rather than some default values which you then change immediately after.

I also strongly agree with Luca D'Alberti – there is no need for your 'preset weapons' to be instance properties. As they don't rely on any instance state, or are unique to a given instance – they should be static.

For example:

class Weapon {

    static var blade : Weapon {
        return Weapon(name: "Blade", index: 0, price: 300, power: 15)
    }

    static var swiftShooter : Weapon {
        return Weapon(name: "Swift Shooter", index: 1, price: 300, attackSpeed: 0.2)
    }

    static var minionsFoot : Weapon {
        return Weapon(name: "Minions Foot", index: 3, price: 300, criticalChance: 0.1, criticalDamage: 0.1)
    }

    var name: String
    var index: Int
    var price: Int
    var power: Int
    var attackSpeed: Double
    var criticalChance: Double
    var criticalDamage: Double

    init(name: String, index: Int, price: Int,
         power: Int = 0, attackSpeed: Double = 0,
         criticalChance: Double = 0, criticalDamage: Double = 0) {

        self.name = name
        self.index = index
        self.price = price
        self.power = power
        self.attackSpeed = attackSpeed
        self.criticalChance = criticalChance
        self.criticalDamage = criticalDamage
    }
}

let blade = Weapon.blade
let swiftShooter : Weapon = .swiftShooter