gpt4 book ai didi

ios - 如何在不使用函数的情况下修改实例值?

转载 作者:行者123 更新时间:2023-11-28 09:54:37 25 4
gpt4 key购买 nike

我有一个类:

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

}

我需要为每个项目设置 weaponPower attackSpeed ...,我这样做时遇到错误。

我找到的答案说你必须使用函数来修改实例的值,但我觉得这会使代码变得复杂,否则我该如何设置它的值?

使用函数的问题是它将创建实例和设置值的过程分开,使代码更难维护。

最佳答案

您应该为类中的所有 weaponItems 添加属性

那么你的类实现应该是这样的

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

var weaponBlade:WeaponItems{

get {
let tempWeaponBlade = WeaponItems(name: "Weapon Blade", index: 0, price: 300)
tempWeaponBlade.weaponPower = 15
return tempWeaponBlade
}
}

var swiftShooter:WeaponItems{

get {
let tempSwiftShooter = WeaponItems(name: "Swift Shooter", index: 1, price: 300)
tempSwiftShooter.attackSpeed = 0.2
return tempSwiftShooter
}
}

var minionsFoot:WeaponItems{

get {
let tempMinionsFoot = WeaponItems(name: "Minions Foot", index: 3, price: 300)
tempMinionsFoot.criticalChance = 0.1
tempMinionsFoot.criticalDamage = 0.1
return tempMinionsFoot
}
}


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

}

关于ios - 如何在不使用函数的情况下修改实例值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39385227/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com