Swift - Protocols

Aus Wikizone
Wechseln zu: Navigation, Suche

Links

Einführung

Protokolle garantieren, dass Klassen oder Structs bestimmte Funktionen haben. Wird der Klasse oder dem Struct ein Protokoll zugewiesen, muss sie die Funktionen des Protokolls implementieren. Wie sie das tut bleibt der Klasse überlassen.

Protokolle kann man als Datentyp verwenden. So kann man bei Funktionsaufrufen z.B. mehrere Klassen erlauben. Wichtig ist dann nur, dass sie die Vorgaben des Protokolls erfüllen. Das Protokoll ist also eine Art Garantie, dass eine Klasse bestimmte Dinge erfüllt.

Man sagt auch eine Klasse adaptiert ein (oder mehrere) Protokoll(e)

class MyClass: Superclass, FirstProtocol, AnotherProtocol, ...

Beispiele

//
//  main.swift
//  Protocol Demo
//
//  Created by Stephan Schlegel on 07.01.23.
//

/**
 Klassen oder Structs mit dem protocol canFly MÜSSEN die Funktion fly() IMPLEMENTIEREN
 Es wird nicht vorgegeben wie diese im Detail aussehen soll. So kann ein Flugzeug
 anders fliegen wie ein Adler
 
 Das Protokoll ist wie ein Zertifikat das GARANTIERT, dass eine Klasse bestimmte FÄHIGKEITEN  hat. Auf der anderen Seite kann man das Protokoll einsetzen, wenn man bestimmte Eigenschaften nicht in der Klasse definieren möchte. Z.B. möchten wir keine fly() Funktion  in der Klasse Birds implementieren, da z.B. Pinguine gar nicht fliegen können.
 
 */
protocol CanFly {
    func fly()
}

class Bird {
    var isFemale = true
    func layEgg(){
        if(isFemale){
            print("The bird makes a new bird in a shell.")
        }
    }
}

// penguins don't fly
class Penguin: Bird {
    func swim(){
        print("The penguin paddles through the water")
    }
}

// eagles do
class Eagle: Bird, CanFly { // ADOPTS CanFly
    func soar(){
        print("The eagle glides in the air using air currents")
    }
    func fly(){
        print("The eagle flaps it's wings and lifts off into the sky")
    }
}

struct Airplane: CanFly { // Structs can use protocols too
    func fly() { //  Airplanes do fly but don't flap wings
        print("The airplane uses it's engine to lift off into the sky")
    }
}

struct FlyingMuseum{
    /**
     We can use the protocol as a DATATYPE. This let's us use different Objects but guarantees that all of them have a fly function
     */
    func flyingShow(flyingObject: CanFly){
        print("Watch our show - ")
        flyingObject.fly()
    }
}
    
// Let's go
let myEagle = Eagle()
let myPenguin = Penguin()
let myPlane = Airplane()
myEagle.fly()
myPlane.fly()
myPenguin.layEgg() // inherited from Bird
let museum = FlyingMuseum()
museum.flyingShow(flyingObject: myPlane) // sure to work because of protocol CanFly
museum.flyingShow(flyingObject: myEagle)

Ausgabe:

The eagle flaps it's wings and lifts off into the sky
The airplane uses it's engine to lift off into the sky
The bird makes a new bird in a shell.
Watch our show - 
The airplane uses it's engine to lift off into the sky
Watch our show - 
The eagle flaps it's wings and lifts off into the sky