Class - Extensions

Eli·2021년 2월 7일
1

Swift

목록 보기
13/17
post-thumbnail

익스텐션을 이용해 기존 이미 정의된 클래스, 구조체, 열거형, 프로토콜 타입에 기능을 추가할 수 있다.

추가 가능한 기능

  1. Computed Property
  2. Method
  3. Initializer
  4. Subscript
  5. Protocol 따르도록
  6. 중첩 타입

Syntax

class SomeType {

}

//기본 문법
extension SomeType {
	//추가기능
}

//Protocol with extension
extension SomeType: SomeProtocol {
}

Example

//연산 프로퍼티
extension Double {
    var km: Double { return self * 1_000.0 }
}

//메소드를 확장
extension Int {
		func multiple(_ value: Int) {
				return self * value
		}
}

//Initializer 확장
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)
    }
}

//Subscript 확장
extension Int {
    subscript(digitIndex: Int) -> Int {
        var decimalBase = 1
        for _ in 0..<digitIndex {
            decimalBase *= 10
        }
        return (self / decimalBase) % 10
    }
}
746381295[0]
// returns 5

#학습에 대한 내용으로 틀린 내용이 있을 수 있습니다.
#댓글로 남겨주시면 더 좋은 게시글로 수정하도록 하겠습니다.

profile
애플을 좋아한다. 그래서 iOS 개발을 한다. @Kurly

0개의 댓글