Skip to content

Latest commit

ย 

History

History
74 lines (54 loc) ยท 2.51 KB

@Published.md

File metadata and controls

74 lines (54 loc) ยท 2.51 KB

@Published

๊ณต์‹๋ฌธ์„œ : A type that publishes a property marked with an attribute.

Declaration

@propertyWrapper struct Published<Value>

Overview

@Published ์†์„ฑ์„ ์‚ฌ์šฉํ•˜๋ฉด ์ด ์œ ํ˜•์˜ ํผ๋ธ”๋ฆฌ์…”(publisher)๊ฐ€ ์ƒ์„ฑ๋œ๋‹ค.

์ด ํ›„ $์—ฐ์‚ฐ์ž๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๋ณ€์ˆ˜๊ฐ’์˜ ๋ณ€ํ™”์— ์ ‘๊ทผํ•  ์ˆ˜ ์žˆ๋‹ค.

ex)

class Weather : ObservableObject {
    @Published var temperature: Double
    init(temperature: Double) {
        self.temperature = temperature
    }
}

let weather = Weather(temperature: 20)
cancellable = weather.$temperature
    .sink() {
        print ("Temperature now: \($0)")
}
weather.temperature = 25

// Prints:
// Temperature now: 20.0
// Temperature now: 25.0

์œ„ ์ฝ”๋“œ ์ฒ˜๋Ÿผ ํ”„๋กœํผํ‹ฐ๊ฐ€ ๋ณ€ํ–ˆ์„ ๋•Œ, willSet ๋ธ”๋ก์— ๊ฒŒ์‹œ๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค.

์ด ๋ง์€, ์‹ค์ œ๋กœ ํ”„๋กœํผํ‹ฐ๊ฐ€ ๋ณ€๊ฒฝ(์„ค์ •)๋˜๊ธฐ ์ „์— ์ƒˆ ๊ฐ’์„ ๋ฐ›๋Š”๋‹ค๋Š” ๋ง์ด๋‹ค.

Temperature now: 20.0์€ ํด๋กœ์ ธ๋ฅผ ์„ ์–ธ ํ–ˆ์„ ๋•Œ ๋ฐ”๋กœ ์ถœ๋ ฅ๋˜๋ฉฐ, ๊ทธ ์ดํ›„ ๋ณ€ํ•œ๊ฐ’์—๋Œ€ํ•œ ์ถœ๋ ฅ์ด ๋‚˜ํƒ€๋‚˜๊ฒŒ ๋œ๋‹ค.

์ถ”๊ฐ€

@Published๋Š” ํ”„๋กœํผํ‹ฐ ๋ž˜ํผ๋กœ ํ”„๋กœํผํ‹ฐ๊ฐ€ ๋ณ€๊ฒฝ์ด ๋ฐœ์ƒํ•  ๋•Œ ์ž๋™์œผ๋กœ ์•Œ๋ ค์ฃผ๋Š” observable object๋ฅผ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋‹ค.

SiwftUI๋Š” ์ด๋Ÿฌํ•œ ๋ณ€๊ฒฝ์‚ฌํ•ญ์„ ๊ด€์ฐฐํ•˜๊ณ  ๋ชจ๋‹ˆํ„ฐ๋งํ•˜๋Š” View์˜ body์†์„ฑ์„ ๋‹ค์‹œ ํ˜ธ์ถœํ•ด ์ค€๋‹ค.

ํ•œ๋งˆ๋””๋กœ @Published๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ๊ทธ ํ”„๋กœํผํ‹ฐ๊ฐ€ ๋ณ€๊ฒฝ ๋  ๋•Œ๋งˆ๋‹ค ํ•ด๋‹น ํ”„๋กœํผํ‹ฐ๋ฅผ ์‚ฌ์šฉํ•˜๋Š” View๋“ค์„ ๋‹ค์‹œ ๋กœ๋“œ ์‹œ์ผœ ์ค€๋‹ค๋Š” ๋ง์ด๋‹ค.

์˜ˆ๋ฅผ ๋“ค์–ด๋ณด์ž,

class Test: ObservableObject {
    var testNumArray = [String]()
}

์œ„์˜ ์˜ˆ์‹œ๋Š” ๊ด€์ฐฐ ๊ฐ€๋Šฅํ•˜๋„๋ก ํ”„๋กœํ† ์ฝœ์„ ์‚ฌ์šฉํ•ด ์ฃผ์–ด์„œ SwiftUI๊ฐ€ ๋ณ€๊ฒฝ ์‚ฌํ•ญ์„ ๊ฐ์‹œํ•ด ์ฃผ๋„๋ก ํ–ˆ๋‹ค.

ํ•˜์ง€๋งŒ ํ”„๋กœํผํ‹ฐ์—๋Š” ์•„๋ฌด๋Ÿฐ ํ”„๋กœํผํ‹ฐ ๋ž˜ํผ๊ฐ€ ์„ ์–ธ ๋˜์–ด ์žˆ์ง€ ์•Š๊ธฐ์— ๋ณ€๊ฒฝ์€ ์ž์œ ์ž์žฌ๋กœ ํ•  ์ˆ˜ ์žˆ์ง€๋งŒ, ๋ณ€๊ฒฝ ์‚ฌํ•ญ์„ ์•Œ๋ ค์ฃผ๊ฑฐ๋‚˜ ํ•˜์ง€ ์•Š๋Š”๋‹ค.

์ด ๋•Œ @Published๋ฅผ ์‚ฌ์šฉ ํ•˜์—ฌ ์ด ์ ์„ ๋ณด์™„ํ•  ์ˆ˜ ์žˆ๋‹ค.

class Test: ObservableObject {
    @Published var testNumArray = [String]()
}

์œ„ ์ฝ”๋“œ๋กœ ๋ฐ”๊ฟ”์„œ ์ž‘์„ฑํ•œ๋‹ค๋ฉด @Published ์†์„ฑ ๋ž˜ํผ๋Š” ํ•ญ๋ชฉ์— willSet ์†์„ฑ ๊ด€์ฐฐ์ž๋ฅผ ์ถ”๊ฐ€ํ•˜์—ฌ ๋ชจ๋“  ๋ณ€๊ฒฝ ์‚ฌํ•ญ์ด observer์—๊ฒŒ ์ž๋™์œผ๋กœ ์ „์†ก ๋œ๋‹ค.

์ด ๋ง์€ ์ฆ‰, testNummArray๊ฐ€ ๋ณ€๊ฒฝ ๋˜์—ˆ์„ ๊ฒฝ์šฐ ํ•ด๋‹น ํ”„๋กœํผํ‹ฐ๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๋ทฐ๋“ค์„ ๋ณ€๊ฒฝํ•œ ๊ฐ’์— ๋Œ€ํ•˜์—ฌ ์ž๋™์œผ๋กœ ๋ฆฌ๋กœ๋“œ ๋œ๋‹ค๋Š” ๋ง์ด๋‹ค.


๊ณต์‹๋ฌธ์„œ