我尝试使用一些更新命名属性的默认方法创建协议。很抱歉,我收到了错误Left side of mutating operator isn't mutable…
protocol Weapon {
var energy: Int { get set }
var fireEnergy: Int { get }
var rechargeRate: Int { get }
func fire()
func recharge()
}
extension Weapon {
var fireEnergy: Int {
return 10
}
var rechargeRate: Int {
return 2
}
func fire() {
guard energy >= fireEnergy else { return }
energy -= fireEnergy // <- Error Here
}
func recharge() {
energy += rechargeRate // <- Error Here
}
}
class PhaseCannon: Weapon {
var energy = 0
}
如果我按照建议将方法更改为变异,那么我在fire方法的使用点会出现错误。 Cannot use mutating member on immutable value…
var weapons = [PhaseCannon()]
for weapon in weapons {
weapon.fire() // <- Error here
}
我可以不这样做吗?
答案 0 :(得分:0)
您的第二个错误是因为周期中的武器是让。最快的修复方法是您可以将代码更改为:
var weapons = [PhaseCannon()]
var newWeapons: [PhaseCannon]
for weapon in weapons {
var updatedWeapon = weapon
updatedWeapon.fire() // <- Error here
newWeapons.append(weapon)
}
答案 1 :(得分:0)
如果重构现有代码允许,我建议将PhaseCannon转换为类而不是结构。
否则你可以改变你的更新循环:
var child_process = require( 'child_process' )
, home = process.env.HOME
;
function exec( command, options, next ) {
if( /cygwin/.test( home ) ) {
command = home.replace( /(cygwin[0-9]*).*/, "$1" ) + "\\bin\\bash.exe -c '" + command.replace( /\\/g, '/' ).replace( /'/g, "\'" ) + "'";
}
child_process.exec( command, options, next );
}