iOS/๐ŸŸ  Swift

[Swift] ํ”„๋กœํ† ์ฝœ ์ƒ์„ฑ์ž ์š”๊ตฌ์‚ฌํ•ญ (Initializer Requirements)

woozzang 2021. 1. 19. 14:36
์ฐธ๊ณ  ์ž๋ฃŒ: Protocols - swift.org

 

Syntax

ํ”„๋กœํ† ์ฝœ์—์„œ Initializer ๋Š” ๋ฉ”์„œ๋“œ ์„ ์–ธ ๋ฐฉ์‹๊ณผ ๋งˆ์ฐฌ๊ฐ€์ง€๋กœ { } (curly brace) ์—†์ด init(...) ๊ณผ ๊ฐ™์€ ๊ผด๋กœ ์„ ์–ธํ•ด์ค๋‹ˆ๋‹ค.

protocol SomeProtocol {
  init(someParameter: Int)
}

 

Protocol ์„ ์ฑ„ํƒํ•œ Class์˜ Initializer ๊ตฌํ˜„

ํ”„๋กœํ† ์ฝœ์„ ์ฑ„ํƒํ•œ ํƒ€์ž…์€ Initializer๋ฅผ designated initializer๋‚˜  convenience initializer๋กœ ๊ตฌํ˜„ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

ํ”„๋กœํ† ์ฝœ์€ class, struct, enum ํƒ€์ž…๋งŒ ์ฑ„ํƒํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 

๋‘ ๊ฒฝ์šฐ ๋ชจ๋‘  `required` ํ‚ค์›Œ๋“œ๋ฅผ initializer ์•ž์— ๋ถ™์—ฌ์ฃผ์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.

 

SomeClass ๋ฅผ ์„œ๋ธŒํด๋ž˜์‹ฑํ•œ ํด๋ž˜์Šค๋“ค๋„  ํ•ด๋‹น ํ”„๋กœํ† ์ฝœ์„ conform ํ•ด์•ผ ํ•˜๊ธฐ ๋•Œ๋ฌธ์ž…๋‹ˆ๋‹ค.

class SomeClass: SomeProtocol {
  required init(someParameter: Int) {
  
    // implementation code
  }
}

 

๋‹จ protocol๋ฅผ ๊ตฌํ˜„ํ•˜๋Š” ํด๋ž˜์Šค๊ฐ€ `final class` ๋ผ๋ฉด  `required` ๋ฅผ ๋ถ™์ผ ํ•„์š”๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค.

 

`final class`๋Š” ์„œ๋ธŒํด๋ž˜์‹ฑ์ด ๋ถˆ๊ฐ€๋Šฅํ•˜๊ธฐ ๋•Œ๋ฌธ์ž…๋‹ˆ๋‹ค.

/* required ํ‚ค์›Œ๋“œ๊ฐ€ ์—†์–ด๋„ Compile Error ๊ฐ€ ๋ฐœ์ƒํ•˜์ง€ ์•Š๋Š”๋‹ค.*/
final class myClass: SomeProtocol {
    init(number: Int) {
        ...
    }
}
๊ด€๋ จ ๊ธ€: Preventing Overrides - swift.org

 

์ถ”๊ฐ€์ ์œผ๋กœ protocol ์„ ์–ธ๋ถ€์—์„œ initializer์•ž์— `final` ์„ ๋ถ™์ผ ์ˆ˜ ์—†๋‹ค๋Š” ์ ์„ ์ƒ๊ธฐํ•˜๊ณ  ๊ฐ€๊ฒ ์Šต๋‹ˆ๋‹ค.


 

Failable Initializer Requirements

protocol Something {
  init?()
}

struct Some: Something {
  init() {
  }
}

ํ”„๋กœํ† ์ฝœ์— ์„ ์–ธ๋œ failable initializer๋ฅผ conforming type์ด non-failable๋กœ ๊ตฌํ˜„ํ•ด๋„ ํ”„๋กœํ† ์ฝœ ์š”๊ตฌ์กฐ๊ฑด์€ ์ถฉ์กฑ๋ฉ๋‹ˆ๋‹ค.

์ฆ‰, init?() ์ด๋‚˜ init!()์œผ๋กœ ์„ ์–ธ๋œ ์ƒ์„ฑ์ž๋ฅผ init() ์œผ๋กœ ๊ตฌํ˜„ํ•˜๋Š” ๊ฒƒ

 

๋ฐ˜๋Œ€๋กœ non-failable initailizer๋Š” non-failable ์ด๊ฑฐ๋‚˜ IUO failable initializer๋กœ ๊ตฌํ˜„ํ•ด์•ผ ํ”„๋กœํ† ์ฝœ ์š”๊ตฌ์กฐ๊ฑด์ด ์ถฉ์กฑ๋ฉ๋‹ˆ๋‹ค.

init()์œผ๋กœ ์„ ์–ธ๋˜์—ˆ๋‹ค๋ฉด init() ์ด๋‚˜ init!() ์œผ๋กœ ๊ตฌํ˜„๋˜์–ด์•ผํ•œ๋‹ค๋Š” ๊ฒƒ

 

โ—๏ธํ”„๋กœํ† ์ฝœ ์š”๊ตฌ์‚ฌํ•ญ์€ ์ตœ์†Œ์กฐ๊ฑด์ด๊ธฐ ๋•Œ๋ฌธ์— ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค.

 

๊ด€๋ จ ๊ธ€: Failable Initializer - Initializer

 

๋!


 

๋‹ค์Œ ๊ธ€: Protocol as Types - Protocols

 

Protocol as Types - Protocols

ํ”„๋กœํ† ์ฝœ์€ First Class Citizen ์ด๊ธฐ ๋•Œ๋ฌธ์—, ํ•˜๋‚˜์˜ ๋…๋ฆฝ์ ์ธ ํƒ€์ž… ( a fully fledged types ) ์œผ๋กœ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ๋”ฐ๋ผ์„œ ์•„๋ž˜ 3๊ฐ€์ง€๊ฐ€ ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค. 1. function, method, initializer ์˜ parameter ์™€..

woozzang.tistory.com