-
swift - Initializer and Deinitializer #5 (Faliable Initializer)swift 2021. 1. 12. 16:21
Nonfailalbe init - 실패를 허용하지 않는 init
그러나??
실패를 허용해야 하는 경우도 존재한다.
예로 파일을 초기화하는 코드같은 경우 파일이 존재한다면 정상적으로 초기화가 진행되겠지만
파일이 존재하지 않거나 어떤 문제로 인해 읽을 수 없다면 runtime err가 발생한다.
Failalbe Init
initializer의 Optional 버전이라고 생각하면 쉽다.
// init? -> 성공시 초기화된 instance가 optional 형식으로 return 실패시 nil // init! -> 성공시 강제 추출된 NonOptional 형식의 instance 실패시 crush struct Position { let x: Double let y: Double init?(x: Double, y: Double) { // 음수면 nil guard x >= 0.0, y >= 0.0 else { return nil } self.x = x self.y = y } init!(value: Double) { guard value >= 0.0 else { return nil } self.x = value self.y = value } } let p = Position(x: 12, y: 34) let p2 = Position(x: -1, y: 0) // b의 자료형을 명시해주면 자동으로 unwrapped된다 var b: Position = Position(value: 12) b // b = Position(value: -1) // 엥? crush 발생하지 않고 nil을 리턴?? IUO 구현이 변경되어서
'swift' 카테고리의 다른 글