Method

이원희·2021년 3월 12일
0

 🐧 Swift

목록 보기
31/32
post-thumbnail

오늘은 Method에 대해서 알아보자.
Method중에서 instance Method와 type Method, class Method에 대해서 알아보자.

공식 문서를 기준으로 작성한다.

Method

Method는 특정 유형과 관련된 함수이다.
class, struct, enum은 instance method를 정의할 수 있다.
instance method는 해당 type의 instance의 캡슐화된 작업을하는 기능이다.

class, struct, enum은 type 자체와 관련된 type method를 정의할 수 있다.
type method는 Objective-C의 class method와 비슷하다.

structenum에 method를 정의할 수 있다는 사실은 C/Objective-C와 주요 차이점이다.
classObjective-C에서 메서드를 정의할 수 있는 유일한 유형이다.
Swift에서는 class, struct, enum에 Method를 정의할 수 있으므로 유연하게 Method를 정의 가능하다.


instance Method

instance method는 특정 class,struct, enum인스턴스에 속하는 함수이다.
인스턴스 property에 접근하고 수정하는 방법을 제공하거나 인스턴스의 목적과 관련된 기능을 제공해 인스턴스의 기능을 지원한다.
instance method는 자신이 속한 type의 특정 인스턴스에서만 호출 할 수 있다.

class Counter {
    var count = 0
    func increment() {
        count += 1
    }
    func increment(by amount: Int) {
        count += amount
    }
    func reset() {
        count = 0
    }
}

let counter = Counter()
counter.increment()
counter.increment(by: 5)
counter.reset()

let counter2 = Counter()
counter2.increment(by: 10)

여기서 increment(), increment(by amount:), reset() 모두 instance method이다.
instance method는 자신이 속한 type의 특정 인스턴스에서만 호출 할 수 있다.
따라서, counter.increment()counter2.increment()는 다른 instance method를 호출하고 있다.

이런식으로 Counter라는 type의 인스턴스가 생성될때 인스턴스 메서드는 같이 생성되는 식이다.


self property

모든 인스턴스에는 self property가 존재하고 이는 인스턴스 자체와 정확하게 동일하다.
self property를 사용해 instance method 내에서 현재 인스턴스를 참조한다.

실제로 코드에 self를 자주 작성할 필요는 없다.
self를 명시적으로 작성하지 않으면 Swift는 현재 인스턴스 property 또는 메서드를 참조하고 있다고 가정한다.

func increment() {
    self.count += 1
}

func increment() {
    count += 1
}

따라서 위와 같이 self.countcount가 같은 property가 같다.

그렇다면 아래의 상황을 한 번 보자.

struct Point {
    var x = 0.0, y = 0.0
    func isToTheRightOf(x: Double) -> Bool {
        return 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")
}

x, y property를 갖는 Point struct를 정의했다.
Point의 인스턴스 메서드인 isToTheRightOf(x:)를 봐보자.
어허... isToTheRightOf(x:)의 파라미터 이름이 Point의 property와 동일하다.
return x > x에서 어떤 x가 인스턴스 property이고, 어떤 x가 파라미터인지 알 수 없다.
위와 같은 상황에서는 파라미터 이름을 우선시하여 self property를 사용해 구별해 주어야 한다.

따라서

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")
}

위와 같이 코드를 변경하면 인스턴스 property x가 파라미터 x보다 큰지에 대해서 반환하는 인스턴스 메서드가 완성할 수 있다.


Type Method

instance method는 특정 type의 인스턴스에서 호출하는 메서드이다.
type 자체에서 호출되는 메서드를 정의할 수도 있다.
type 자체!!! 어디서 들어보지 않았는지...!
Property Series - Type Property 여기서 type property를 다룰때 나왔었다.ㅋㅋㅋ

type property를 정의할 때와 마찬가지로 static 키워드를 앞에 붙여서 type method를 정의할 수 있다.
class에서는 static 키워드 대신 class를 사용해 type method를 정의할 수도 있다.
이때 class 키워드가 붙으면 sub class가 super class의 메서드를 재정의 할 수 있다.

class Test {
    let x: Int
    let y: Int 
    
    init(x: Int, y: Int) {
        self.x = x
        self.y = y
    }
    
    static func printTest() {
        print("this is test")
    }
}

Test.printTest()

하나씩 확인해보자.
init()의 파라미터 이름이 인스턴스 property와 동일해서 self로 구별해주고 있다.
static 키워들르 사용해 printTest()를 type method로 정의했다.
따라서 Test.printTest()를 사용할 수 있게 되었다.

그렇다면 class method를 만들어 보자.

class Test {
    let x: Int
    let y: Int 
    
    init(x: Int, y: Int) {
        self.x = x
        self.y = y
    }
    
    class func printTest() {
        print("this is test")
    }
}

Test.printTest()

흠... static 키워드를 class로 바꿔보았다.
아직은 차이점을 모르겠다.

class Test {
    let x: Int
    let y: Int 
    
    init(x: Int, y: Int) {
        self.x = x
        self.y = y
    }
    
    class func printTest() {
        print("this is test")
    }
}

class SubTest: Test {
    override class func printTest() {
        super.printTest()
        print("this is sub test")
    }
}

SubTest.printTest()

Test class를 상속받는 SubTest class를 정의했다.
위에서 class 키워드를 붙이면 sub class에서 super class의 메서드를 재정의할 수 있다고 했다.
SubTest class에서 printTest()를 재정의하고 있다.

결과는

this is test
this is sub test

이렇게 나온다.


정리

instance method, type method, class method에 대해서 알아봤다.

instance method는 class, struct, enum에 정의할 수 있다.
인스턴스 내의 property에 접근할 수 있고, 인스턴스의 기능을 지원하는 역할을 한다.
해당 타입의 인스턴스에서만 호출할 수 있ㄹ다.

type method는 static 키워드와 함께 정의되며 class, struct, enum에 정의할 수 있다.
타입에 대해 정의하는 메서드이다.

class method는 type method와 비슷하다.
class 키워드와 함께 정의되며 이름과 맡게 class에만 정의할 수 있다.
이는 Objective-C에서는 메서드를 정의할 수 있는 곳이 class뿐였고, 그걸 따라 내려온 개념이기 때문이다.
type method와 다른 점이 있다면 sub class에서 super class의 메서드를 재정의할 수 있다는 것이다.


마무리

오늘은 메서드에 대해서 정리해봤다.
사실 이거도 안에 들어가면 다룰 내용이 꽤 있어보이는데... 오늘은 여기까짘ㅋㅋㅋ
그럼 이만👋

0개의 댓글