[swift] Swift 클래스 초기화 관련 Best Practice

Swift에서 클래스를 초기화할 때는 몇 가지 Best Practice를 따를 수 있습니다. 이러한 Best Practice를 따르면 코드의 가독성이 향상되고 오류가 줄어들 수 있습니다. 이 글에서는 Swift 클래스 초기화에 관련된 몇 가지 Best Practice를 알아보겠습니다.

1. Designated Initializer를 정의하세요

Designated Initializer는 클래스의 주요 초기화 메서드입니다. 이 메서드는 모든 속성 값을 설정하고, 상위 클래스의 초기화 메서드를 호출하는 역할을 합니다. 클래스에는 하나 이상의 Designated Initializer를 정의할 수 있으며, 모든 Designated Initializer는 동일한 매개변수 목록을 가져야 합니다.

class MyClass {
    var property1: Int
    var property2: String
    
    init(property1: Int, property2: String) {
        self.property1 = property1
        self.property2 = property2
    }
}

2. Convenience Initializer를 활용하세요

Convenience Initializer는 보조적인 역할을 수행하는 초기화 메서드입니다. 이 메서드는 초기화를 간소화하고, 다양한 초기화 방법을 제공하기 위해 사용됩니다. Convenience Initializer는 해당 클래스 내에서 Designated Initializer를 호출하여 초기화를 수행해야 합니다.

class MyClass {
    var property1: Int
    var property2: String
    
    init(property1: Int, property2: String) {
        self.property1 = property1
        self.property2 = property2
    }
    
    convenience init(property1: Int) {
        self.init(property1: property1, property2: "Default")
    }
}

3. Initializer Chaining을 사용하세요

Initializer Chaining은 여러 초기화 메서드를 협력하여 효율적으로 초기화하는 방법입니다. 클래스 내에서 Designated Initializer를 호출하여 상위 클래스의 초기화 메서드를 실행한 후, Convenience Initializer를 호출하여 보조적인 초기화를 수행할 수 있습니다.

class MyBaseClass {
    var baseProperty: Int
    
    init(baseProperty: Int) {
        self.baseProperty = baseProperty
    }
}

class MyClass: MyBaseClass {
    var property1: Int
    var property2: String
    
    init(property1: Int, property2: String) {
        self.property1 = property1
        self.property2 = property2
        super.init(baseProperty: 0)
    }
    
    convenience init(property1: Int) {
        self.init(property1: property1, property2: "Default")
    }
}

결론

Swift 클래스를 초기화하는 과정에서 위의 Best Practice를 활용하면 가독성이 향상되고, 코드의 오류 가능성이 줄어듭니다. 이러한 가이드라인을 따르면 초기화 코드를 깔끔하게 유지할 수 있습니다.

더 자세한 내용은 Swift 공식 문서에서 확인할 수 있습니다.