Skip to content

Instantly share code, notes, and snippets.

@Oni-zerone
Forked from gabrielepalma/static.swift
Created December 18, 2018 15:24
Show Gist options
  • Select an option

  • Save Oni-zerone/db30fcd8c46ea932ba2322a5d461ffbc to your computer and use it in GitHub Desktop.

Select an option

Save Oni-zerone/db30fcd8c46ea932ba2322a5d461ffbc to your computer and use it in GitHub Desktop.

Revisions

  1. Oni-zerone revised this gist Dec 18, 2018. 1 changed file with 14 additions and 9 deletions.
    23 changes: 14 additions & 9 deletions static.swift
    Original file line number Diff line number Diff line change
    @@ -1,29 +1,34 @@
    struct Dog : Animal {
    func eat() {
    print("dog eats")
    }
    func talk() {
    print("dog talk")

    var animalType: String {
    return "dog"
    }
    }

    protocol Animal {
    func talk()

    var animalType: String { get }
    }

    extension Animal {

    var animalType: String {
    return "animal"
    }

    func eat() {
    print("animal eats")
    print("\(animalType) eats")
    }
    func talk() {
    print("animal talk")
    print("\(animalType) talk")
    }


    }

    func animalDoAnimalStuff(animal : Animal) {
    animal.eat()
    // eat is defined in extension, thus it is statically dispatched and will print "animal eats"

    animal.talk()
    // talk is declared in the protocol, thus it is dynamically dispatched and will print "dog talk"
    }
  2. @gabrielepalma gabrielepalma revised this gist Dec 18, 2018. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion static.swift
    Original file line number Diff line number Diff line change
    @@ -25,7 +25,7 @@ func animalDoAnimalStuff(animal : Animal) {
    // eat is defined in extension, thus it is statically dispatched and will print "animal eats"

    animal.talk()
    // talk is defined in the protocol, thus it is dynamically dispatched and will print "dog talk"
    // talk is declared in the protocol, thus it is dynamically dispatched and will print "dog talk"
    }

    let dog = Dog()
  3. @gabrielepalma gabrielepalma created this gist Dec 18, 2018.
    32 changes: 32 additions & 0 deletions static.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,32 @@
    struct Dog : Animal {
    func eat() {
    print("dog eats")
    }
    func talk() {
    print("dog talk")
    }
    }

    protocol Animal {
    func talk()
    }

    extension Animal {
    func eat() {
    print("animal eats")
    }
    func talk() {
    print("animal talk")
    }
    }

    func animalDoAnimalStuff(animal : Animal) {
    animal.eat()
    // eat is defined in extension, thus it is statically dispatched and will print "animal eats"

    animal.talk()
    // talk is defined in the protocol, thus it is dynamically dispatched and will print "dog talk"
    }

    let dog = Dog()
    animalDoAnimalStuff(animal: dog)