[Swift] Methods

East Silver·2021년 12월 30일
0

애플 공식 문서를 바탕으로 정리합니다!

Instance Methods

The self Property

인스턴스 메서드의 매개변수 이름이 인스턴스의 프로퍼티와 이름이 같은 경우에는 반드시 self를 명시적으로 작성하여 이를 구별해줘야 한다.

Modifying Value Types from Within Instance Methods

기본적으로 값 타입의 프로퍼티는 인스턴스 메서드 내에서 수정할 수 없다. 하지만 만약 구조체나 열거형의 인스턴스 메서드에서 프로퍼티를 수정해야 한다면 mutating을 메서드 앞에 써줘서 이를 가능하게 만들 수 있다. 이렇게 정의한 메서드는 새로운 인스턴스를 암시적으로 할당할 수 있고 새로운 인스턴스는 메서드가 종료될 때 기존 인스턴스를 대체하게 된다.

struct Point {
    var x = 0.0, y = 0.0
    mutating func moveBy(x deltaX: Double, y deltaY: Double) {
        x += deltaX
        y += deltaY
    }
}
var somePoint = Point(x: 1.0, y: 1.0)
somePoint.moveBy(x: 2.0, y: 3.0)
print("The point is now at (\(somePoint.x), \(somePoint.y))")
// Prints "The point is now at (3.0, 4.0)"

Assigning to self Within a Mutating Method

Mutating methods can assign an entirely new instance to the implicit self property

struct Point {
    var x = 0.0, y = 0.0
    mutating func moveBy(x deltaX: Double, y deltaY: Double) {
        self = Point(x: x + deltaX, y: y + deltaY)
    }
}

Mutating methods for enumerations can set the implicit self parameter to be a different case from the same enumeration:

enum TriStateSwitch {
    case off, low, high
    mutating func next() {
        switch self {
        case .off:
            self = .low
        case .low:
            self = .high
        case .high:
            self = .off
        }
    }
}
var ovenLight = TriStateSwitch.low
ovenLight.next()
// ovenLight is now equal to .high
ovenLight.next()
// ovenLight is now equal to .off

Type Methods

타입 메서드를 정의하는 방법은 func 키워드 앞에 static이라는 키워드를 써주면 된다. 클래스에서는 class 키워드로 이를 대체하며 이는 상속받은 자식 클래스에서 부모 클래스의 메서드를 override 하여 재정의 할 수 있게 하기 위해서다.

profile
IOS programmer가 되고 싶다

0개의 댓글