-
MethodsiOS/Swift 공식문서 2022. 2. 19. 15:01
Method란?
특정 타입(열거형, 구조체, 클래스)에 관련된 함수를 말한다.
Instance Methods
특정 타입의 인스턴스에 속한 함수를 말한다. 인스턴스 프로퍼티에 접근하는 등 해당 인스턴스의 기능을 지원할 때 사용한다. 해당 인스턴스를 통해서만 호출될 수 있다. 예를 들어
Counter
클래스에서count
프로퍼티와 3개의 인스턴스 메서드를 정의할 수 있다.class Counter { var count = 0 func increment() { count += 1 } func increment(by amount: Int) { count += amount } func reset() { count = 0 } }
counter
라는Counter
클래스의 인스턴스를 생성한 다음counter
를 통해 3개의 메서드를 호출할 수 있다.let counter = Counter() // the initial counter value is 0 counter.increment() // the counter's value is now 1 counter.increment(by: 5) // the counter's value is now 6 counter.reset() // the counter's value is now 0
The self Property
self
는 타입의 모든 인스턴스가 암시적으로 갖고 있는 프로퍼티로, 인스턴스 그 자체이다.Counter
클래스 안에서count
를 1씩 증가시키는increment()
메서드를 다음과 같이 정의할 수 있다. 이 메서드에서는self
를 따로 적지 않아도 해당 인스턴스에count
에 접근할 수 있다.func increment() { self.count += 1 }
그러나
self
를 꼭 적어야 하는 경우가 존재하는데, 매개변수와 이름이 겹치는 경우이다. 프로퍼티와 매개변수를 구분하기 위해self
를 반드시 적어야 한다.struct Point { var x = 0.0, y = 0.0 func isToTheRightOf(x: Double) -> Bool { return self.x > x } } let somePoint = Point(x: 4.0, y: 5.0) if somePoint.isToTheRightOf(x: 1.0) { print("This point is to the right of the line where x == 1.0") } // Prints "This point is to the right of the line where x == 1.0"
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)"
구조체와 열거형은 value type이기 때문에 상수로 선언하면 프로퍼티를 바꾸지 못하므로 주의하자.
let fixedPoint = Point(x: 3.0, y: 3.0)
Assigning to self Within a Mutating Method
mutating 메서드에서
self
프로퍼티 값을 바꾸는 것도 가능하다. 그러면 새로운 인스턴스가 기존 인스턴스를 대신할 것이다.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) } }
다음과 같이 열거형에서 case 순환을 구현할 수 있다.
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
타입 그 자체에서 호출하는 메서드를 말한다. 타입 프로퍼티와 마찬가지로 선언 앞에
static
키워드를 붙인다. 클래스의 경우class
키워드를 대신 사용할 수 있는데, subclass에서 오버라이딩을 허용하기 위해 사용한다.class SomeClass { class func someTypeMethod() { // type method implementation goes here } } SomeClass.someTypeMethod()
타입 메서드의 경우 안에서
self
를 사용하면 해당 타입 자체를 가리키게 된다. 타입 프로퍼티와 타입 메서드의 매개변수를 구분하기 위해 사용한다.일반적으로 해당 타입 내에서 사용할 수 없는 프로퍼티나 메서드 이름은 다른 타입의 타입 메서드나 타입 프로퍼티로 간주된다. 따라서 타입의 이름을 명시하지 않고도 다른 타입의 타입 프로퍼티나 메서드를 사용할 수 있다.
Reference
https://docs.swift.org/swift-book/LanguageGuide/Methods.html
'iOS > Swift 공식문서' 카테고리의 다른 글
Inheritance (0) 2022.02.20 Subscripts (0) 2022.02.19 Properties (0) 2022.02.18 Structures and Classes (0) 2022.02.17 Enumerations (0) 2022.02.16