Swift - Extension

Aus Wikizone
Wechseln zu: Navigation, Suche

Links

Swift (Programmiersprache)

Einleitung

Extensions erweitern Funktionalitäten von Typen.

Vorhandene Funktionen von Typen können erweitert werden, solange die Übergebenen Parameter sich von anderen Aufrufen unterscheiden.

Beispiele

Beispiel: Double erweitern

/**
 Extensions can extend the functionality of all types. Even the basic types.
 In this example we extend the Double Type
 */
import UIKit

var doubleOne = 3.1415926
var doubleTwo = doubleOne

doubleOne.round()
// round rounds to whole number
print(doubleOne)
// but if we want sth. like round(to: 3)
// to round to three decimals?
// We can extend the native Double datatype

extension Double{
    func round(to places:Int)->Double{
        let multiplier = pow(10.0, Double(places) )
        var n = self
        n = n * multiplier
        n.round()
        n = n / multiplier
        return n
    }
}

// and now we have extended the Double.round() function
print(doubleTwo.round(to: 3))

Beispiel UIButton erweitern

import UIKit

extension UIButton{
    func makeCircular(){
        self.clipsToBounds = true
        self.layer.cornerRadius = CGFloat(self.frame.height / 2)
    }
}

let button = UIButton(frame: CGRect(x:0, y:0, width:50, height:50))
button.backgroundColor = .red
// Instead of ...
// button.layer.cornerRadius = 25
// button.clipsToBounds = true
// we can now:

button.makeCircular()

Protocol Extensions

Mit Erweiterungen von Protokollen kann man das Standardverhalten definieren.

Allgemein

extension SomeProtocol{
  // Default behaviour
}
import UIKit

/***/
protocol CanFly{
    func fly()
}

extension CanFly{
    func fly(){
        print("The object lifts off into the air...")
    }
}

/**
 Normally each class which adopts the CanFly protocol would have
 to implement the fly() Method
 
 As we EXTEND CanFly protocol with a default version of the
 fly function all adopting Object also adopt this fly() version
 automatically.
 */
class Plane: CanFly{
}

class Bird: CanFly{
    func fly(){
        print("The bird flaps it's wings and lifts off into the sky")
    }
}

let cessna = Plane()
let blackbird = Bird()

cessna.fly()
blackbird.fly()

// Output:
// The object lifts off into the air...
// The bird flaps it's wings and lifts off into the sky