[Swift] Property Wrapper

Lenaยท2021๋…„ 8์›” 31์ผ
1

Swift 5.1์—์„œ ์ถ”๊ฐ€๋œ ๊ฐœ๋…์ด๋‹ค.
Property Wrapper(๊ฐ์‹ธ๋Š”) ์ด๋ฆ„๋‹ต๊ฒŒ ์ค‘๋ณต์ด ๋˜๋Š” ๋กœ์ง์„ ํฌํ•จํ•˜๋Š” ํƒ€์ž…์„ ์ •์˜ํ•œ๋‹ค.

Struct, Enum, Class์—์„œ Wrapping ํ•˜๊ณ  ์‹ถ์€ property ์•ž์— @State ๊ฐ™์€ attribute๋ฅผ ๋ช…์‹œํ•ด์„œ ์‚ฌ์šฉํ•œ๋‹ค.

Example

WWDC 19 ์˜ˆ์ œ ์ฝ”๋“œ,
UserDefaults์— ๊ฐ’์„ ์ €์žฅํ•˜๊ณ  ๊ฐ€์ ธ์˜ค๊ธฐ ์œ„ํ•œ ์ฝ”๋“œ๊ฐ€ ์ค‘๋ณต๋œ๋‹ค.

class UserManager {
  static var useTouchID: Bool {
    get { UserDefaults.standard.bool(forKey: "useTouchID") }
    set { UserDefaults.standard.set(newValue, forKey: "useTouchID") }
  }
  
  static var userEmail: String? {
    get { UserDefaults.standard.string(forKey: "userEmail") }
    set { UserDefaults.standard.set(newValue, forKey: "userEmail") }
  }

  static var isLoggedIn: Bool {
    get { UserDefaults.standard.bool(forKey: "isLoggedIn") }
    set { UserDefaults.standard.set(newValue, forKey: "isLoggedIn") }
  }
}

Property Wrapper๋ฅผ ์ด์šฉํ•ด ์ค‘๋ณต ์ฝ”๋“œ๋ฅผ wrapping ํ•ด๋ณด๋ฉด ์•„๋ž˜์™€ ๊ฐ™๊ณ ,

@propertyWrapper
struct UserDefault<T> {

  let key: String
  let defaultValue: T

  var wrappedValue: T {
    get { UserDefaults.standard.object(forKey: key) as? T ?? defaultValue }
    set { UserDefaults.standard.set(newValue, forKey: key) }
  }
}

์ด๋ฅผ ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

class UserManager {
  @UserDefault(key: "useTouchID", defaultValue: false)
  static var useTouchID: Bool
  
  @UserDefault(key: "userEmail", defaultValue: nil)
  static var userEmail: String?
  
  @UserDefault(key: "isLoggedIn", defaultValue: false)
  static var isLoggedIn: Bool
}

โž•

DI์— ํ™œ์šฉ

  • DIContainer ๊ฐ์ฒด๋กœ๋ถ€ํ„ฐ ์ธ์Šคํ„ด์Šค๋ฅผ get ํ•˜๋Š” ๋กœ์ง์„ Property wrapper๋กœ ๊ฐ์‹ผ ์˜ˆ์ œ์ด๋‹ค.
  • ViewController ์•ˆ์—์„œ View Model๋ฅผ ์ƒ์„ฑํ•˜์ง€ ์•Š๊ณ  ์ฃผ์ž…๋ฐ›์„ ์ˆ˜ ์žˆ๋‹ค.
@propertyWrapper
struct Dependency<T> {
  var wrappedValue: T {
    DIContainer.shared.resolve()
  }
}

// in ViewController
@Dependency var moviesViewModel: MoviesViewModel

~์ •๋ฆฌ~

property ์•ž์— attribute๊ฐ€ ๋ถ™์œผ๋ฉด, Property Wrapper์˜ wrappedValue๋กœ ์‚ฌ์šฉํ•˜๊ฒ ๋‹ค๋Š” ์˜๋ฏธ์ด๋‹ค.
Property Wrapper๋ฅผ ์‚ฌ์šฉํ•ด์„œ ์ฝ”๋“œ์˜ ์ค‘๋ณต์„ ์ค„์ผ ์ˆ˜ ์žˆ๋‹ค.

Property Wrapper
[DI] DI Container, IOC Container ๊ฐœ๋…๊ณผ ์˜ˆ์ œ

0๊ฐœ์˜ ๋Œ“๊ธ€