今日、Swift の構造とクラスについて学んでいたので、新しく見つけた知識を使って、以前に作成した戦闘計算機を合理化することにしました。これで、func で呼び出されるプロパティは本質的にローカル変数であり、さらに「let」定数であることがわかりました。したがって、以下のコードにエラーがある理由はわかりますが、理解できないのは、nil 合体演算子 (??) を使用してコードをさらに複雑にすることなく目標を達成する方法です。
アドバイスをいただければ幸いです。
import Foundation
import Glibc
struct Unit {
enum UnitType: String {
case sniper
case shocktrooper
case infantry
case support
}
let name: String
let type: UnitType
var hitPoints: Int
let attackStrength: Int
//attack another unit
mutating func attack(target: Unit) {
print("\(self.name) is attacking \(target.name)...")
if self.attackStrength > target.attackStrength {
print("\(self.name) hit \(target.name) for
\(self.attackStrength) points of damage!")
target.hit(target, self.attackStrength) /*error: cannont use
muatating member on imutable value: 'target is a 'let' constant */
} else {
self.repelled(by: target.attackStrength)
}
}
//take damage from defender
mutating func repelled(by damage: Int) {
self.hitPoints -= damage
print("\(name) was repelled and took \(damage) points of damage!")
}
//take damage from attack
mutating func hit(for damage: Int) {
self.hitPoints -= damage
}
}
//declaring two seperate units
var player1 = Unit(name: "Player 1", type: .sniper, hitPoints: 10,
attackStrength: 3)
var player2 = Unit(name: "Player 2", type: .shocktrooper, hitPoints: 15,
attackStrength: 2)
func score() {
print("The current hitpoints are: \(player1.name): \(player1.hitPoints)
& \(player2.name): \(player2.hitPoints)")
}
player1.attack(target: player2)
score()