Swift - Classes

Aus Wikizone
Wechseln zu: Navigation, Suche

Links

Swift (Programmiersprache)

Unterschiede zu Structs

  • Classes werden by reference übergeben. Kopiert man die Instanz einer Klasse greift man technisch gesehen mit beiden Namen auf das selbe Objekt zu (siehe unten)

Beispiele

main.swift

let skeleton = Enemy(health: 100, attackStrength: 10)
print("Skeleton health: \(skeleton.health)")
skeleton.move()

// other than structs classes are passed by reference
let skeleton2 = skeleton // skeleton 2 is areferenced to the same object as skeleton
skeleton.takeDamage(amount: 20) // both skeletons have health 80 now
print("Skeleton health: \(skeleton.health)")
print("Skeleton2 health: \(skeleton2.health)")

let dragon = Dragon(health:300, attackStrength: 10)
dragon.wingSpan = 5
dragon.attackStrength = 15
dragon.move()
dragon.attack()
dragon.talk(speech: "My teeth are swords! My claws are speers! My wings are a hurricane")

Enemy.swift

class Enemy {
    var health: Int
    var attackStrength: Int
    
    init(health: Int, attackStrength: Int){
        self.health = health
        self.attackStrength = attackStrength
    }
    
    func takeDamage(amount: Int){
        print("Take Damage: \(amount)")
        health -= amount // other than struct this works in classes without mutable
    }
    func move(){
        print("Walk forwards")
    }
    
    func attack(){
        print("Land a hit, does \(attackStrength) damage")
    }
}

Dragon.swift

class Dragon: Enemy { // Inherits from Enemy class
    var wingSpan = 2 // additional property
    
    func talk(speech: String){ // additional function
        print("Says: \(speech)")
    }
    
    override func move() { // override a function from superclass
        print("Fly forwards")
    }
    
    override func attack() {
        super.attack() // trigger function of superclass (parentclass)
        print("Spits fire and does 10 damage")
    }
}

Output:

100
Walk forwards
Land a hit, does 10 damage
Fly forwards
Land a hit, does 15 damage
Spits fire and does 10 damage
Says: My teeth are swords! My claws are speers! My wings are a hurricane