TIL (Today I Learned) 240118_Initializer

Danny·2024년 1월 20일

TIL(Today I Learned)

목록 보기
16/34

1월 18일 (목)

🔥학습 내용

이니셜라이저(Initializer)

1. Intialization(초기화)란 무엇인가?

  • Initialization is the process of preparing an instance of a class, structure, or enumeration for use.
    이니셜라이제이션(초기화)는 클래스, 구조체, 열거형 인스턴스 생성의 준비 과정이다.

2. Initializer란 무엇인가?

  • 특정 타입의 인스턴스를 생성할 때, 사용된다.
  • 구조는 아래와 같다.
init() {
    // perform some initialization here
}
  1. Property를 초기화를 했다면, Initializer를 대체할 수 있습니다.
struct Fahrenheit {
    var temperature = 32.0
}
  1. Initializer에는 Property를 초기화 시켜준다.
struct Celsius {
    var temperatureInCelsius: Double
    init(fromFahrenheit fahrenheit: Double) {
        temperatureInCelsius = (fahrenheit - 32.0) / 1.8
    }
    init(fromKelvin kelvin: Double) {
        temperatureInCelsius = kelvin - 273.15
    }
}
let boilingPointOfWater = Celsius(fromFahrenheit: 212.0)
// boilingPointOfWater.temperatureInCelsius is 100.0
let freezingPointOfWater = Celsius(fromKelvin: 273.15)
// freezingPointOfWater.temperatureInCelsius is 0.0
  1. Optional Property의 경우, 이니셜라이저의 사용이 되지 않는다면, 자동으로 nil으로 초기화된다.
class SurveyQuestion {
    var text: String
    var response: String?
    init(text: String) {
        self.text = text
    }
    func ask() {
        print(text)
    }
}
let cheeseQuestion = SurveyQuestion(text: "Do you like cheese?")
cheeseQuestion.ask()
// Prints "Do you like cheese?"
print(cheeseQuestion.response) // nil
cheeseQuestion.response = "Yes, I do like cheese."
  1. Constant Property(상수)가 있다면 Initialization할 때 꼭 할당해야한다.
class SurveyQuestion {
    let text: String
    var response: String?
    init(text: String) {
        self.text = text
    }
    func ask() {
        print(text)
    }
}
let beetsQuestion = SurveyQuestion(text: "How about beets?")
beetsQuestion.ask()
// Prints "How about beets?"
beetsQuestion.response = "I also like beets. (But not with cheese.)"

#. 참고 URL

  1. Initialization: https://docs.swift.org/swift-book/documentation/the-swift-programming-language/initialization
profile
안녕하세요 iOS 개발자 지망생 Danny 입니다.

0개의 댓글