[iOS] Property 초기화 방법 정리

HL·2022년 5월 8일
0

iOS

목록 보기
20/22

프로퍼티를 초기화하는 두 가지 방법이 무슨 차이가 있는지 궁금해서 찾아봤다

Initializers

struct Fahrenheit {
    var temperature: Double
    init() {
        temperature = 32.0
    }
}

Default Property Values

struct Fahrenheit {
    var temperature = 32.0
}

If a property always takes the same initial value, provide a default value rather than setting a value within an initializer. The end result is the same, but the default value ties the property’s initialization more closely to its declaration. It makes for shorter, clearer initializers and enables you to infer the type of the property from its default value. The default value also makes it easier for you to take advantage of default initializers and initializer inheritance, as described later in this chapter.

  • 항상 같은 값을 가질 때 사용 가능
  • 결과적으로는 똑같음
  • 값을 선언과 더 가까이 결합시켜줌 >> 짧고 명확, 알기 쉬움
  • 기본 생성자, 생성자 상속을 더 쉽게 활용할 수 있음

링크

자세한 내용은 공식 문서에 더 있다
https://docs.swift.org/swift-book/LanguageGuide/Initialization.html

profile
Frontend 개발자입니다.

0개의 댓글