TIL/Swift 내용 정리

Swift Deep Dive: Convenience init

여의도사노비 2023. 2. 16. 19:46
728x90

Convenience init은 뭘까?

🤖 In Swift, a convenience initializer (convenience init) is a special type of initializer that provides a shortcut to create an instance of a class or a structure. A convenience initializer is defined using the convenience keyword before the init keyword. It must call another initializer (either a designated initializer of the same class/struct or a superclass initializer) before it can set the properties of the instance.

Swift에서 Convenience init은 클래스 또는 구조체의 인스턴스를 생성하는 지름길을 제공하는 특별한 유형의 init입니다.

Convenience init은 인스턴스의 속성을 설정하기 전에 다른 init(Designated or Superclass)를 호출해야 합니다.

 

🙋🏻‍♂️ 말이 어려운데 결국 Convenience init도 그냥 init(Designated init)과 같은 유형의 init이다. 단지 Convenience init은 인스턴스를 더 쉽고 빠르게 생성할 수 있도록 돕는 역할을 한다고 생각하면 된다. 그리고 Designated init이 선언되어야 Convenience init도 생성이 가능하다. 그 이유는 아래에서 보자.

 

🤖 The main purpose of a convenience initializer is to simplify the initialization process by providing default values or by allowing initialization with a subset of the parameters of the designated initializer. It can also be used to provide a more convenient syntax for creating an instance.

Convenience init의 주요 목적은 기본값을 제공하거나 Designated init의 매개변수 하위 집합으로 초기화를 허용하여 초기화 프로세스를 단순화하는 것입니다. 인스턴스 생성을 위한 보다 편리한 구문을 제공하는 데 사용할 수도 있습니다.

 

🙋🏻‍♂️ 여기서 Designated init이 먼저 선언되어야 하는 이유가 나온다. Convenience init은
1) 기본값을 제공하거나
2) init의 매개변수 하위 집합을 이용하여 초기화를 할 수 있다.
결국 init에서 선언한 매개변수들을 활용해야 하기 때문에 Desingated init의 매개변수들이 먼저 선언되어야 하는 것이다.

이는 굉장히 복잡하고 많은 매개변수를 포함하는 init을 조금 더 쉽게 사용할 수 있게 만들어준다. 예를 들면 Designated init의 매개변수가 5개인데 우리가 자주 사용하는 매개변수는 2개이다. 이때 이 2개 조차도 값은 항상 'Male', '10'으로 고정되어 있다. 이런 경우 Convenience init을 활용하여 자주 사용하는 매겨변수의 값을 고정해놓고 사용할 수 있는 것이다.

 

말로만 들으면 감이 안오니 코드로 보자!

class Person {
    var name: String
    var age: Int
    
    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }
    
    convenience init(name: String) {
        self.init(name: name, age: 0)
    }
    // 위에 선언된 init의 매개변수(name, age)를 convenience init에서 다시 가져와 할당할 수 있다.
    // 위의 예시는 name은 init과 같은 형태로 argument를 받고, age의 경우는 상수 0으로 고정시켰다.
}

let person1 = Person(name: "John", age: 30)
let person2 = Person(name: "Jane")
// 위처럼 covenience init을 활용하는 경우 person2처럼 인스턴스를 생성할 때 age 파라미터는 굳이 건드리지 않아도
// age에 0이 초기값으로 할당되어 편하다.