Swift - Classes: Unterschied zwischen den Versionen

Aus Wikizone
Wechseln zu: Navigation, Suche
(Die Seite wurde neu angelegt: „== Links == Swift (Programmiersprache) == Beispiele == main.swift <syntaxhighlight lang="Swift"> let skeleton = Enemy() print(skeleton.health) skeleton.move(…“)
 
Zeile 53: Zeile 53:
 
}
 
}
 
</syntaxhighlight>
 
</syntaxhighlight>
 +
 +
Output:
 +
<pre>
 +
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
 +
</pre>

Version vom 3. Januar 2023, 21:48 Uhr

Links

Swift (Programmiersprache)

Beispiele

main.swift

let skeleton = Enemy()
print(skeleton.health)
skeleton.move()
skeleton.attack()

let dragon = Dragon()
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 = 100
    var attackStrength = 10
    
    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