extension ์์ ํ ์ ์๋ ๊ฒ
extension SomeType {
// ์ถ๊ฐํ ๊ธฐ๋ฅ ์ ์
}
extension SomeType: SomeProtocol, AnotherProtocol {
// ํ๋กํ ์ฝ ํ์ ํ๋กํผํฐ, ํจ์ ์ ์
}
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"
convenience init
๋ง ์ถ๊ฐ ๊ฐ๋ฅ.designated init
์ด๋ deinit ์ ๋ถ๊ฐ๋ฅ.// ์ด๊ธฐ๊ฐ์ด ์๊ณ custom init ์์
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)
}
}
extension Int {
func repetitions(task: () -> Void) {
for _ in 0..<self {
task()
}
}
}
3.repetitions { print("wink") }
extension Int {
mutating func square() {
self = self * self
}
}
var someInt = 3
someInt.square()
// someInt is now 9
extension Int {
subscript(digitIndex: Int) -> Int {
var decimalBase = 1
for _ in 0..<digitIndex {
decimalBase *= 10
}
return (self / decimalBase) % 10
// 10 * n๋ฒ์งธ ์๋ก ํ์ฌ ์๋ฅผ ๋๋ ๊ฒ์ ๋๋จธ์ง
// 1์ธ ๊ฒฝ์ฐ 746381295 % 10 -> 5๊ฐ ๋๋จธ์ง
// 2์ธ ๊ฒฝ์ฐ 746381295 % 10 -> 9๊ฐ ๋๋จธ์ง
}
}
746381295[0] // 5
746381295[1] // 9
746381295[2] // 2
746381295[8] // 7
746381295[9] // 0
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("- ", terminator: "")
case .zero:
print("0 ", terminator: "")
case .positive:
print("+ ", terminator: "")
}
}
print("")
}
printIntegerKinds([3, 19, -27, 0, -6, 0, 7])
// Prints "+ + - 0 - 0 + "
convenience
๋ง ์ ์ ๊ฐ๋ฅ ํ๊ณ ,๋ฉด์ ์คํฐ๋ ํ ์ถ๊ฐ.
์ถ์ฒ
https://bbiguduk.gitbook.io/swift/language-guide-1/extensions
https://feather.tistory.com/2