Skip to content

Latest commit

ย 

History

History
65 lines (45 loc) ยท 2.34 KB

@State.md

File metadata and controls

65 lines (45 loc) ยท 2.34 KB

@State

๊ณต์‹๋ฌธ์„œ : A property wrapper type that can read and write a value managed by SwiftUI.

Declaration

@frozen @propertyWrapper struct State<Value>

Overview

@State๋Š” SwiftUI์—์„œ ํ•ด๋‹น ํ”„๋กœํผํ‹ฐ๊ฐ€ ํ•˜๊ณ ์‹ถ์€ ํ–‰๋™์„ ์ •์˜ํ•˜๋Š” ํƒ€์ž…์ด๋ผ๊ณ  ํ•œ๋‹ค.

์ดํ•ดํ•ด ๋ณด์ž๋ฉด @State๋กœ ์„ ์–ธ๋œ ๋ณ€์ˆ˜๋“ค์€ ๊ฐ’์ด ๋ณ€๊ฒฝ๋˜๋Š” ๊ฒฝ์šฐ, View๋ฅผ invalidate(๋ฌดํšจํ™”)ํ•˜๊ณ  var body:some View ๋ฅผ recompute ํ•˜๊ฒŒ ํ•œ๋‹ค.

@State ๋ณ€์ˆ˜๋Š” View ๋˜๋Š” View์—์„œ ํ˜ธ์ถœ๋œ ๋ฉ”์„œ๋“œ์—์„œ๋งŒ ์ ‘๊ทผํ•ด์•ผ ํ•œ๋‹ค. ํ•œ๋งˆ๋””๋กœ @State๋ณ€์ˆ˜์— ์‚ฌ์šฉ์ž๊ฐ€ ์ง์ ‘์ ์œผ๋กœ ์ ‘๊ทผํ•˜์ง€ ๋ชปํ•˜๋„๋ก ์“ฐ๋ ˆ๋“œ์—์„œ ๋ณ€๊ฒฝํ•˜๋Š” ๊ฒƒ์ด ์•ˆ์ „ํ•˜๋‹ค.

๊ทธ๋ž˜์„œ ์ฃผ๋กœ @State ๋ณ€์ˆ˜๋ฅผ Private๊ณผ ํ•จ๊ป˜ ์‚ฌ์šฉํ•˜๋ฉฐ ํ•ด๋‹น ๋ณ€์ˆ˜๋ฅผ ๋‹ค๋ฅธ View์— ์ „๋‹ฌํ•˜๊ณ ์ž ํ•œ๋‹ค๋ฉด, $๋ฅผ ์ด์šฉํ•˜์—ฌ ์ „๋‹ฌํ•œ๋‹ค.

ex)

struct Landmark: view{
    @Binding var showFavoritesOnly : Bool
    
    var body: some View{
        Label("Toggle Favroite", systemImage: showFavoritesOnly ? "star.fill" : "star")
    }
}   

struct LandmarkList: view{
    @State private var showFavoritesOnly = false
    
    ...
    var body: some View{
        ...
        Toggle(isOn: $showFavoritesOnly){
            Text("Favorites only")
        }
    }
}

์ถ”๊ฐ€

SwiftUI์—์„œ View(๊ตฌ์กฐ์ฒด)์•ˆ์— ์„ ์–ธ๋œ ํ”„๋กœํผํ‹ฐ ๊ฐ’์„ ๊ตฌ์กฐ์ฒด ๋‚ด์—์„œ ๋ณ€๊ฒฝํ•˜๋ ค๊ณ  ํ•˜๋ฉด ์˜ค๋ฅ˜๊ฐ€ ๋‚œ๋‹ค.

Swift์˜ ๊ตฌ์กฐ์ฒด์—์„œ mutating์œผ๋กœ ์„ ์–ธ๋˜์ง€ ์•Š์€ ํ”„๋กœํผํ‹ฐ๋Š” ๊ตฌ์กฐ์ฒด ๋‚ด์—์„œ ๊ทธ ๊ฐ’์˜ ๋ณ€๊ฒฝ์ด ๋ถˆ๊ฐ€ํ•˜๋‹ค.

๊ทธ๋ ‡๋‹ค๊ณ  ์—ฐ์‚ฐ ํ”„๋กœํผํ‹ฐ์ธ body๋ฅผ mutating์œผ๋กœ ์„ ์–ธํ•ด ์ฃผ์–ด๋„ ์•ˆ๋œ๋‹ค.

-> Viewํ”„๋กœํ† ์ฝœ์˜ body ํ”„๋กœํผํ‹ฐ๋Š” {get}์œผ๋กœ ์„ ์–ธ๋˜์–ด ์žˆ์œผ๋ฉฐ, ์ด๋Š” nonmutating์œผ๋กœ ๊ตฌํ˜„์„ ์š”๊ตฌํ•œ๋‹ค.

๊ทธ๋ ‡๋‹ค๋ฉด ์–ด๋–ป๊ฒŒ ํ”„๋กœํผํ‹ฐ ๊ฐ’์„ ๋ณ€๊ฒฝํ•  ์ˆ˜ ์žˆ์„๊นŒ?

์ด ๋•Œ @State๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ํ”„๋กœํผํ‹ฐ ๊ฐ’์„ ๊ฐ•์ œ๋กœ ๋ณ€๊ฒฝํ•  ์ˆ˜ ์žˆ๊ฒŒ ๋œ๋‹ค.

ํ•˜์ง€๋งŒ @State๋ฅผ ์‚ฌ์šฉํ•œ๋‹ค๊ณ  ํ•ด๋„ ์ปดํŒŒ์ผ ์—๋Ÿฌ๋Š” ํ”ผํ•  ์ˆ˜ ์žˆ์ง€๋งŒ ์‹คํ–‰ ํ™”๋ฉด์—์„œ๋Š” ๋ณ€๊ฒฝ์ด ์•ˆ๋œ ๊ฒƒ์„ ํ™•์ธ ํ•  ์ˆ˜ ์žˆ๋‹ค.

-> @State ์†์„ฑ์˜ ํ”„๋กœํผํ‹ฐ ๊ฐ’์€ ์‚ฌ์‹ค ์žฌ ํ• ๋‹นํ•˜์—ฌ ๊ฐ’์„ ๋ฐ”๊ฟ€ ์ˆ˜ ์—†๋‹ค.

@Binding์„ ์‚ฌ์šฉํ•ด์•ผ๋งŒ ๋ณ€๊ฒฝ์ด ๊ฐ€๋Šฅํ•˜๋‹ค.

@Binding์— ๋Œ€ํ•ด์„œ๋Š” ํ•ด๋‹น ๊ธ€์—์„œ ๋‹ค๋ฃจ๊ฒ ๋‹ค.


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