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.

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 <syntaxhighlight lang="swift"> 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()