Swift - Classes

Aus Wikizone
Version vom 3. Februar 2023, 20:51 Uhr von 134.3.86.14 (Diskussion) (→‎Beispiele)
(Unterschied) ← Nächstältere Version | Aktuelle Version (Unterschied) | Nächstjüngere Version → (Unterschied)
Wechseln zu: Navigation, Suche

Links[Bearbeiten]

Swift (Programmiersprache)

Klassen in Swift[Bearbeiten]

Im Wesentlichen gelten die gleichen Konzepte wie in anderen Programmiersprachen. In einer Klasse gibt es Properties und Methods und es gelten Konzepte wie Vererbung.

Das self Keyword wird genutzt um aus der Klasse auf Objekte der. Klasse selbst zuzugreifen. Self kann in Swift auch weggelassen werden, solange die Zuordnung für den Compiler eindeutig ist. Die Frage ist was übersichtlicher ist. Mit oder ohne self.

Eigenschaften von Klassen und Vergleich zu Structs[Bearbeiten]

  • 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)
  • Immutable
  • Das ist effektiv aber auch gefährlicher, da leichter Fehler entstehen können.
  • Apple empfielt wenn möglich mit Structs zu beginnen und nur wenn notwendig auf Klassen zurückzugreifen.
Struct Class Erklärung
struct MyStruct {} class MyClass: SuperClass {} Beide sind gleich konstruiert. Klassen können vererbt werden (SuperClass / SubClass)
Immutable Mutable Wenn Werte in Structs verändert werden wird das komplette Objekt zerstört und mit dem neuen Wert neu angelegt. Der Compiler möchte deshalb das Keyword mutating vor Funktionen die Werte verändern. Das funktioniert auch mit let Konstanten. In Klassen können Funktionen alle vars verändern. Let Konstanten aber nicht
passed by value passed by reference Bei Stucts werden Kopien weitergegeben, bei Klassen eine Referenz auf das Original

Beispiele[Bearbeiten]

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

Instanzen von Klassen vergleichen[Bearbeiten]

How can I check if two instances of a class are the same?

In Swift, you can check if two instances of a class are the same by using the equality operator (==) or the identity operator (===).

The equality operator == checks if two instances have the same values for their properties. In order for this to work, the class must conform to the Equatable protocol and implement the == operator:

class MyClass: Equatable {
    let property: Int

    static func == (lhs: MyClass, rhs: MyClass) -> Bool {
        return lhs.property == rhs.property
    }
}

let instance1 = MyClass(property: 1)
let instance2 = MyClass(property: 1)
let isEqual = instance1 == instance2 // true

The identity operator === checks if two instances refer to the same memory address. It checks if two instances are the same instance.

let instance1 = MyClass(property: 1)
let instance2 = MyClass(property: 1)
let isIdentical = instance1 === instance2 // false

Note: It is recommended to use the === operator if you need to check if two instances are the same instance, and use the == operator if you need to check if two instances have the same values for their properties.