[Swift learning] Swift programming tour-expansion (24), swift tour
An extension adds new features to an existing class, struct, or enumeration type, including attributes and Methods. If you define an extension to add new features to an existing type, this new function is available to all existing instances of this type, even if they are defined before your extension.
Extended syntax
Declare an extension using the key extension, and add the type name after the extension
extension SomeType { }
An extension can expand an existing type so that it can adapt to one or more protocols ). In this case, the interface name should be written in the form of class or struct Name:
extension SomeType: SomeProtocol, AnotherProctocol { }
Extension of computing attributes
extension Double {
var km: Double { return self * 1_000.0 }
var m: Double { return self }
var cm: Double { return self / 100.0 }
var mm: Double { return self / 1_000.0 }
var ft: Double { return self / 3.28084 }
}
let oneInch = 25.4.mm
print("One inch is \(oneInch) meters")
// Prints "One inch is 0.0254 meters"
let threeFeet = 3.ft
print("Three feet is \(threeFeet) meters")
// Prints "Three feet is 0.914399970739201 meters
Note: You can add new computing attributes for extensions, but you cannot add storage attributes or add property observers to existing attributes ).
Constructor
Extension can add a new constructor to an existing type. This allows you to extend other types, take your custom type as the constructor parameter, or provide additional initialization options not included in the original implementation of this type.
Note: If you use an extension to add a constructor to a value type, the constructor provides default values for all storage properties and does not define any custom Constructor (custom initializers ), you can call the default initializers and memberwise initializers for value types in your extended constructor ). As described in the Value Type constructor authorization, if you have written the constructor as part of the original implementation of the value type, the above rules are no longer applicable.
Method extension
extension Int {
func repetitions(task: () -> ()) {
for i in 0..self {
task()
}
}
}
This repetitions method uses a ()-> () type single argument), indicating that the function has no parameters and no return value.
After defining the extension, you can call the repetitions Method for any integer. The function is to execute a task multiple times:
3.repetitions{
println("Goodbye!")
}
// Goodbye!
// Goodbye!
// Goodbye!