728x90
안녕하세요.
갑자기 Swift 언어 공식 문서에 꽂혀서... 기초를 다질 겸 틈틈이 보고 있습니다ㅎㅎ
오늘은 구조체 생성자에 대한 내용 간단하게 정리해볼게요.
# 1. Initializer Delegation
생성자(initializer)는 인스턴스 초기화를 하기 위해 다른 생성자를 호출할 수 있고 이런 과정을 'Initializer Delegation'이라고 부릅니다.
# 2. 구조체에서 self.init는 생성자에서만 호출할 수 있습니다.
구조체 안에서 생성자 외에 다른 곳(함수 등)에선 self.init을 호출할 수 없어요.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct Person { | |
let name: String | |
let age: Int | |
func foo() { | |
// ❎ Error: 'init' is a member of the type; use 'type(of: ...)' to initialize a new object of the same dynamic type | |
// self.init(name: "philip", age: 19) | |
} | |
} |
# 3. 커스텀 생성자를 만든 경우 default 생성자를 사용할 수 없습니다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct Person { | |
let name: String | |
let age: Int | |
init() { | |
// ❎ Error: Argument passed to call that takes no arguments | |
// self.init(name: "12", age: 10) | |
} | |
} |
# 4. extension 안에 커스텀 생성자를 넣은 경우 default 생성자를 쓸 수 있습니다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct Person { | |
let name: String | |
let age: Int | |
} | |
extension Person { | |
init() { | |
self.init(name: "philip", age: 19) // ✅ OK! | |
} | |
} |
# 참고
Documentation
docs.swift.org
이번 글은 여기서 마무리.
반응형
'Swift' 카테고리의 다른 글
Memory Safety (1) | 2024.01.25 |
---|---|
클래스(class type) 생성자에 대해 알아보자 (0) | 2024.01.21 |
private(set) (0) | 2024.01.17 |
@available (0) | 2023.12.05 |
@testable (0) | 2023.11.21 |