스위프트 문법 : Extensions (영)

김영채 (Kevin)·2021년 1월 18일
0

iOS & Swift

목록 보기
32/107
post-thumbnail

Extensions add new functionality to an existing class, structure, enumeration, or protocol type.

Extensions in Swift can:

  • Add computed instance properties and computed type properties
  • Define instance methods and type methods
  • Provide new initializers
  • Define subscripts
  • Define and use new nested types
  • Make an existing type conform to a protocol

Extensions can add new functionality to a type, but they cannot override existing functionality.

An extension can extend an existing type to make it adopt one or more protocols. To add protocol conformance, you write the protocol names the same way as you write them for a class or structure:

extension SomeType: SomeProtocol, AnotherProtocol {
    // implementation of protocol requirements goes here
}

→ "Adding Protocol Conformance with an Extension."

Computed Properties

  • Extensions can add computed type properties to existing types.
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"

→ Adding 5 computed instance properties to the type: Double.

Extensions can add new computed properties, but they cannot add stored properties, or add property observers to existing properties.

Initializers

Extensions can add new initializers to existing types. This enables you to extend other types to accept your own custom types as initializer parameters, or to provide additional initialization options that were not included as part of the type’s original implementation.

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()
}

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)
    }
}

Methods

Extensions can add new instance methods and type methods to existing types

extension Int {
    func repetitions(task: () -> Void) {
        for _ in 0..<self {
            task()
        }
    }
}

3.repetitions {
    print("Hello!")
}
// Hello!
// Hello!
// Hello!

Mutating Instance Methods

Instance methods added with an extension can also modify (or mutate) the instance itself.

extension Int {
    mutating func square() {
        self = self * self
    }
}
var someInt = 3
someInt.square()
	// someInt is now 9
profile
맛있는 iOS 프로그래밍

0개의 댓글