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.

/**
 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))