swift 공식 문서
[iOS - swift 공식 문서] 11. Methods (메서드)
jake-kim
2021. 6. 29. 00:32
Method
- 메서드의 정의: 특정 유형과 관련된 함수
- 인스턴스 작업을 위한 특정 작업
Instance Method
- 특정 클래스, 구조, 열거 형의 인스턴스에 속하는 함수
class Counter {
var count = 0
func increment() {
count += 1
}
func increment(by amount: Int) {
count += amount
}
func reset() {
count = 0
}
}
let counter = Counter() // 1
counter.increment() // 1
counter.increment(by: 5) // 6
counter.reset() // 0
Self Property
- 클래스 내에서 self의 의미: 자체 인스턴스 메서드 내에서 현재 인스턴스를 참조
- self는 암시적 속성이므로 생략 가능
func increment() {
self.count += 1
}
- 매개변수와 인스턴스 속성을 구별할때 사용
struct Point {
var x = 0.0, y = 0.0
func isToTheRightOf(x: Double) -> Bool {
return self.x > x
}
}
Instance Method 내에서 Value Type 값 수정
- Struct, Enum은 value type이므로 Instance Method내에서 수정이 불가하지만, mutating func를 통해 해당 메서드의 동작을 '변경'하도록 설정
struct Point {
var x = 0.0, y = 0.0
mutating func moveBy(x deltaX: Double, y deltaY: Double) {
x += deltaX
y += deltaY
}
}
// enum에서의 mutating func 사용
enum TriStateSwitch {
case off, low, high
mutating func next() {
switch self {
case .off:
self = .low
case .low:
self = .high
case .high:
self = .off
}
}
}
Type Method
- Instance Method는 특정 유형의 Instance에서 호출되는 메서드
- Type Method는 Type자체에서 호출되는 메서드
- static func
- class func (수퍼 클래스 구현을 재정의 가능)
class SomeClass {
class func someTypeMethod() {
// type method implementation goes here
}
}
SomeClass.someTypeMethod()
* 참고
https://docs.swift.org/swift-book/LanguageGuide/Methods.html