조앤의 기술블로그
[Swift] Initializers #1 본문
생성자(Initializers)는 클래스, 구조체, 열거형에서
인스턴스를 생성할 때 값을 초기화하여 인스턴스를 만들 수 있도록 하는 것입니다.
struct Figure {
var width: Double
var height: Double
init() {
width = 0.0
height = 0.0
}
}
var f = Figure()
print("The default value is \(width) x \(height)")
// 0.0 0.0
[Parameter Names and Argument Labels]
생성자의 파라미터를 지정할 수도 있습니다.
struct Color {
let red, green, blue: Double
init(red: Double, green: Double, blue: Double) {
self.red = red
self.green = green
self.blue = blue
}
init(white: Double) {
red = white
green = white
blue = white
}
}
let magenta = Color(red: 1.0, green: 0.0, blue: 1.0)
let halfGray = Color(white: 0.5)
let veryGreen = Color(0.0, 1.0, 0.0)
// 이 경우 컴파일 에러가 납니다.
// argument label을 써주어야 합니다.
Customizing Initialization
[Initializer Parameters Without Argument Labels]
argument label을 생략하고 싶은 경우, 와일드카드 패턴을 이용하여 _ 키워드를 사용하면 됩니다.
struct Celsius {
var temperatureInCelsius: Double
init(fromFahrenheit fahrenheit: Double) {
temperatureInCelsius = (fahrenheit - 32.0) / 1.8
}
init(fromKelvin kelvin: Double) {
temperatureInCelsius = kelvin - 273.15
}
init(_ celsius: Double) {
temperatureInCelsius = celsius
}
}
let boilingPointOfWater = Celsius(fromFahrenheit: 212.0)
// 100.0
let freezingPointOfWater = Celsius(fromKelvin: 273.15)
// 0.0
let bodyTemperature = Celsius(37.0)
[Optional Property Types]
옵셔널 속성을 생성자에서 초기화할 때는 아직 값이 없는 것으로 간주하므로 초기화에서 생략합니다.
(intended to have "no value yet" during initialization)
class SurveyQuestion {
var text: String
var response: String?
init(text: String) {
self.text = text
}
func ask() {
print(text)
}
}
let BTSQuestion = SurveryQuestion(text: "Do you know BTS?")
BTSQuestion.ask()
// Prints "Do you know BTS?"
BTSQuestion.response = "Yes, I do know BTS."
Deafault Initailizers
어떠한 생성자도 만들지 않고, 선언할 때 기본 값이 있다면 기본 생성자가 제공됩니다.
이 경우에는 속성을 선언할 때 초기화를 한 값으로 초기화가 됩니다.
class ShoppingListItem {
var name: String?
var quantity = 1
var purchased = false
}
var item = ShoppingListItem()
[Memberwise Initializers for Structure Types]
구조체 형식은 어떠한 생성자도 만들지 않았을 경우, 자동적으로 'memberwise Initializer'를 제공받게 됩니다.
기본 생성자와는 다르게 기본값이 없더라도 memberwise initializer을 제공받습니다.
struct Size {
var width = 0.0, height = 0.0
}
let twoByTwo = Size(width: 2.0, height: 2.0)
멤버와이즈 생성자를 호출할 경우, 기본값이 있는 속성을 생략할 수 있습니다.
(you can omit values for any properties that have default values.)
let zeroByTwo = Size(height: 2.0)
print(zeroByTwo.width, zeroByTwo.height)
// Prints "0.0 2.0"
let zeroByZero = Size()
print(zeroByZero.width, zeroByZero.height)
// Prints "0.0 0.0"
Initializer Delegation에 대한 내용은 다음 포스팅에서 다루겠습니다.
감사합니다.
참고, 코드 인용: https://docs.swift.org/swift-book/LanguageGuide/Initialization.html
'Study > Swift' 카테고리의 다른 글
[Swift] Extension (익스텐션) (0) | 2020.02.27 |
---|---|
[Swift] Initializers #2 (0) | 2020.02.26 |
[Swift] Type Casting (타입 캐스팅) (0) | 2020.02.25 |
[Swift] Inheritance and Polymorphism(상속과 다형성) (0) | 2020.02.24 |
[Swift] Method and Subscript (0) | 2020.02.21 |