Swift) 익스텐션(Extension)

Havi·2021년 1월 15일
0

Swift기초

목록 보기
13/19
post-custom-banner

Extension

import Foundation

// Syntax
extension SomeType: SomeProtocol, AnotherProtocol {
    // implement protocol requirements
}


// func, computed property
extension Int {
    mutating func square() {
        self = self * self
    }

    var km: Int { return self * 1_000} // _는 자리수 구별을 위한 문법
}

var ten = 10

print(ten.km) // 10_000

ten.square() // ten = 100

print(ten)


// Initializer
struct Rect {
    var width: Int
    var height: Int
}

let square: Rect = Rect(width: 10, height: 10) // memberwise Initializer

extension Rect {
    init(center: Int, size: Int) {
        // do something
    }
}


// Nested Type
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
        }
    }
}


// Subscript
extension Int {
    subscript(index: Int) -> Int {
        var decimal = 1

        for _ in 0..<index {
            decimal *= 10
        }

        return (self / decimal) % 10
    }
}

print(746381295[0]) // returns 5
profile
iOS Developer
post-custom-banner

0개의 댓글