Swift - Extension: Unterschied zwischen den Versionen
Aus Wikizone
(Die Seite wurde neu angelegt: „== Links == Swift (Programmiersprache) == Einleitung == Extensions erweitern vorhandene Funktionalitäten Allgemeine Form <pre> extension SomeType{ // Fu…“) |
|||
| Zeile 3: | Zeile 3: | ||
== Einleitung == | == Einleitung == | ||
| − | Extensions erweitern | + | Extensions erweitern Funktionalitäten von Typen. |
| − | + | Vorhandene Funktionen von Typen können erweitert werden, '''solange die Übergebenen Parameter sich von anderen Aufrufen unterscheiden.''' | |
| − | < | + | |
| − | extension | + | <syntaxhighlight lang="swift"> |
| − | + | /** | |
| + | 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)) | ||
| + | </syntaxhighlight> | ||
Version vom 20. Januar 2023, 12:38 Uhr
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))