Struct VS Class

lwb112·2021년 12월 28일
0

class

reference
Passed by reference
inheritance
주소를 공유 즉, 하나의 개체

class Enemy {
    var health: Int
    var attackStrength: Int
    init(health: Int, attackStrength: Int){
        self.health = health
        self.attackStrength = attackStrength
    }
    
    func takeDamage(amount: Int){
        health = health - amount
    }
    func move() {
        print("Walk forwards.")
    }
    func attack() {
        print("Land a hit, does \(attackStrength) damage.")
    }
}
//inheritance ↓ (상속)
class Dragon: Enemy {
    var wingSpan = 2
    
    func talk(speech: String) {
        print("Says: \(speech)")
    }
    override func move() {  // move() == from Enemy Class so, override
        print("Fly forward")
    }
    override func attack() {
        super.attack()
        print("Spits fire, does 10 damage")
    }
}

let skeleton1 = Enemy(health: 100, attackStrength: 10)
let skeleton2 = skeleton1

skeleton1.takeDamage(amount: 10)
skeleton1.takeDamage(amount: 10)
skeleton2.takeDamage(amount: 10)

print(skeleton1.health) //result = 70
print(skeleton2.health) //result = 70

struct

immutable
copy
Passed by Value
값을 복사함 즉, 각각의 개체를 만들 수 있다

struct Enemy {
    var health: Int
    var attackStrength: Int
    init(health: Int, attackStrength: Int){
        self.health = health
        self.attackStrength = attackStrength
    }
    
    mutating func takeDamage(amount: Int){
        health = health - amount
    }
    func move() {
        print("Walk forwards.")
    }
    func attack() {
        print("Land a hit, does \(attackStrength) damage.")
    }
}// can't inheritance ↓ (상속불가)
//class Dragon: Enemy {
//    var wingSpan = 2
//    
//    func talk(speech: String) {
//        print("Says: \(speech)")
//    }
//    override func move() {  // move() == from Enemy Class so, override
//        print("Fly forward")
//    }
//    override func attack() {
//        super.attack()
//        print("Spits fire, does 10 damage")
//    }
//}
var skeleton1 = Enemy(health: 100, attackStrength: 10)
var skeleton2 = skeleton1

skeleton1.takeDamage(amount: 10)
skeleton1.takeDamage(amount: 10)
skeleton2.takeDamage(amount: 10)

print(skeleton1.health) //result = 80
print(skeleton2.health) //result = 90
profile
IOS 앱개발 공부

0개의 댓글