Swift Tutorial - Tutorialspoint

(backadmin) #1

Functionality of an existing class, structure or enumeration type can be added with the
help of extensions. Type functionality can be added with extensions but overriding the
functionality is not possible with extensions.


Swift Extension Functionalities:


 Adding computed properties and computed type properties

 Defining instance and type methods

 Providing new initializers

 Defining subscripts

 Defining and using new nested types

 Making an existing type conform to a protocol

Extensions are declared with the keyword 'extension'


Syntax


extension SomeType {
// new functionality can be added here
}

Existing type can also be added with extensions to make it as a protocol standard and its
syntax is similar to that of classes or structures.


extension SomeType: SomeProtocol, AnotherProtocol {
// protocol requirements is described here
}

Computed Properties


Computed 'instance' and 'type' properties can also be extended with the help of
extensions.


extension Int {
var add: Int {return self + 100 }
var sub: Int { return self - 10 }
var mul: Int { return self * 10 }

30. SWIFT – EXTENSIONS

Free download pdf