๊ณต๋ถ€ ์—ฐ์Šต์žฅ :-)

extension์—์„œ Override

|

@objc

superํด๋ž˜์Šค์—์„œ extension์œผ๋กœ ํ•จ์ˆ˜๋ฅผ ์ถ”๊ฐ€ํ•˜๊ณ  subํด๋ž˜์Šค์—์„œ override ํ•˜๊ณ ์‹ถ์„๋• @objcํ‚ค์›Œ๋“œ๋ฅผ ๋ถ™์—ฌ์•ผํ•œ๋‹ค.

๋ฐœ๊ฒฌ

UIView extension์—์„œ ์ƒˆ๋กœ์šด ํ•จ์ˆ˜๋ฅผ ์„ ์–ธํ•˜๊ณ  ๋‹ค๋ฅธ ์ปค์Šคํ…€๋ทฐ(UIViewํƒ€์ž…)์—์„œ ํ•ด๋‹น ํ•จ์ˆ˜ ๋‚ด๋ถ€๋ฅผ ์ข€ ๋‹ค๋ฅด๊ฒŒ ์“ฐ๊ณ ์‹ถ์–ด์„œ override๋ฅผ ์„ ์–ธํ•˜๋‹ˆ๊นŒ, Overriding non-@objc declarations from extensions is not supported๋ผ๋Š” ์—๋Ÿฌ ๋ฐœ๊ฒฌ.

ํ•ด๊ฒฐ

๊ทธ๋Ÿผ @objc ๋ถ™์ด๋ฉด ํ•ด๊ฒฐ!

class MySuperClass {

}

extension MySuperClass {
    @objc func otherNumber() -> Int {
        return 1
    }
}

class MySubclass : MySuperClass {
    @objc override func otherNumber() -> Int {
        return 2
    }
}

var sup = MySuperClass()
var sub = MySubclass()
print(sup.otherNumber()) // 1
print(sub.otherNumber()) // 2

(๊ณ ๋ฏผ)

  • ์ฒ˜์Œ์— ์ด ๋ฐฉ๋ฒ•์„ ์“ฐ๋ ค๊ณ  ํ–ˆ๋˜๊ฑด ์ปค์Šคํ…€ ๋ทฐ ํด๋ž˜์Šค์—์„œ๋„ ๋น„์Šทํ•œ ๋™์ž‘์„ ํ•ด์•ผํ•˜์ง€๋งŒ, UIViewํด๋ž˜์Šค์— ์„ ์–ธํ•ด๋†“์€ ๊ฒƒ ์ฒ˜๋Ÿผ ์™„์ „ํžˆ ๊ฐ™๊ฒŒ ๋™์ž‘ํ•  ์ˆ˜๋Š” ์—†์–ด์„œ์˜€์Œ
  • ๋น„์Šทํ•œ ๋™์ž‘์ด๊ณ , ๊ฐ™์€ ํด๋ž˜์Šคํƒ€์ž…์ด๋‹ˆ๊นŒ ๊ฐ™์€ ์ด๋ฆ„์œผ๋กœ ์‚ฌ์šฉํ•˜๊ณ ์‹ถ์–ด์„œ overrideํ–ˆ๋˜ ๊ฒƒ์ธ๋ฐ,
  • ์• ์ดˆ์— ํ•ด๋‹น ํƒ€์ž…์—๋‹ค๊ฐ€ ํ•„์š”ํ•œ ํ•จ์ˆ˜๋ฅผ extension์œผ๋กœ ๊ตฌํ˜„ํ•ด๋†“๊ณ  ๊ทธ ํ•จ์ˆ˜๋ฅผ ๋˜ overrideํ•ด์„œ ๋ณ€๊ฒฝํ•˜๊ณ  ์‚ฌ์šฉํ•˜๋Š”๊ฒŒ ํ•ฉ๋ฆฌ์ ์ธ๊ฑธ๊นŒ?

Comments