Extension - gpeegpee/learn-swift GitHub Wiki
Extension
Contents
-
what extensions can do in Swift
- Add functions and computed properties(κ³μ° μμ±κ³Ό κ³μ° μ μ μμ± μΆκ°, μΈμ€ν΄μ€ λ©μλμ νμ λ©μλ μ μ)
- Provide new initializers, i.e. constructor functions(μλ‘μ΄ μ΄λμ λΌμ΄μ μ 곡)
- Define subscripts with the subscript() function(μλΈμ€ν¬λ¦½νΈ μ μ)
- Define and use new nested types, i.e. add a subtype to a type(μλ‘μ΄ μ€μ²© νμ μ μμ μ¬μ©)
- Make an existing type conform to a protocol, which is super useful(κΈ°μ‘΄ νμ μ νλ‘ν μ½ μ μ©νκΈ°)
- Add default implementations to protocols with protocol extensions
-
Remark
- νμ₯μ νμ μ μλ‘μ΄ κΈ°λ₯μ μΆκ°ν μ μμ§λ§ κΈ°μ‘΄ κΈ°λ₯μ μ€λ²λΌμ΄λ ν μ μλ€.
- νμ₯μ μλ‘μ΄ κ³μ° μμ±μ μΆκ°ν μ μμ§λ§, μ μ₯ μμ±μ΄λ κΈ°μ‘΄ μμ±μ μμ± κ°μμλ₯Ό μΆκ°ν μ μλ€.
- http://minsone.github.io/mac/ios/swift-extensions-summary
- http://minsone.github.io/programming/swift3-if-protocol-extension-and-concreated-impletement-have-same-method
- http://minsone.github.io/programming/swift3-protocol-extension-static-dynamic-dispatch
- http://minsone.github.io/programming/swift4-grouping-with-protocol-extension
-
Usage of extension
- Separating and grouping code
- Using protocol conformance
- Namespaced constants
- Extensions, computed properties and helpers
- Protocol extensions
- https://learnappmaking.com/swift-extensions-how-to/
Details
- Syntax
// Extensions
/*
extension SomeType {
// new functionality to add to SomeType goes here
}
extension SomeType: SomeProtocol, AnotherProtocol {
// implementation of protocol requirements goes here
}
*/
- Computed Properties
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")
let threeFeet = 3.ft
print("Three feet is \(threeFeet) meters")
let aMarathon = 42.km + 195.m
print("A marathon is \(aMarathon) meters long")
// Extensions can add new computed properties, but they cannot add stored properties, or add property observers to existing properties.
- Initializers
// Initializers
struct Size {
var width = 0.0, height = 0.0
}
struct Point {
var x = 0.0, y = 0.0
}
struct Rect {
var origin = Point()
var size = Size()
}
let defaultRect = Rect()
let memberwiseRect = Rect(origin: Point(x: 2.0, y:2.0), size: Size(width: 5.0, height: 5.0))
extension Rect {
init(center: Point, size: Size) {
let originX = center.x - (size.width / 2)
let originY = center.y - (size.height / 2)
self.init(origin: Point(x: originX, y: originY), size: size)
}
}
let centerRect = Rect(center: Point(x: 4.0, y: 4.0), size: Size(width: 3.0, height:3.0))
- method
// Methods
extension Int {
func repetitions(task: () -> Void) {
for _ in 0..<self {
task()
}
}
}
3.repetitions {
print("Hello!")
}
// Mutating Instance Methods
extension Int {
mutating func square() {
self = self * self
}
}
var someInt = 3
someInt.square()
someInt
- subsripts
// Subscripts
// This example adds an integer subscript to Swiftβs built-in Int type. This subscript [n] returns the decimal digit n places in from the right of the number:
extension Int {
subscript(digitIndex: Int) -> Int {
var decimalBase = 1
for _ in 0..<digitIndex {
decimalBase *= 10
}
return (self / decimalBase) % 10
}
}
746381295[0]
746381295[1]
746381295[2]
746381295[8]
// If the Int value does not have enough digits for the requested index, the subscript implementation returns 0, as if the number had been padded with zeros to the left:
746381295[9]
- Nested Types
// Nested Types
extension Int {
enum Kind {
case negative, zero, positive
}
var kind: Kind {
switch self {
case 0:
return .zero
case let x where x > 0:
return .positive
default:
return .negative
}
}
}
func printIntegerKinds(_ numbers: [Int]) {
for number in numbers {
switch number.kind {
case .negative:
print("-")
//print("- ", terminator: false)
case .zero:
print("0")
//print("0 ", terminator: false)
case .positive:
print("+")
//print("+ ", terminator: false)
}
}
print("")
}
printIntegerKinds([3, 19, -27, 0, -6, 0, 7])
Reference
-
https://medium.com/@abhimuralidharan/swift-extensions-for-uidevice-4270647ddad0
-
https://medium.com/swift-snippets/swift-snippet-13-extension-oriented-api-69bb5cf80c8c
-
https://medium.com/fantageek/grouping-extension-methods-in-swift-81a2b1409228
-
https://medium.com/ios-os-x-development/swift-protocol-extension-method-dispatch-6a6bf270ba94
-
https://medium.com/@anitaa_1990/extensions-in-swift-5c95859743ab
-
https://medium.com/fantageek/extension-in-swift-47de064ca181