SwiftUI State初始化器的区别

11

在初始化一个@State变量时,有两个初始化器:

/// Initialize with the provided initial value.
public init(wrappedValue value: Value)

/// Initialize with the provided initial value.
public init(initialValue value: Value)

这两种初始化器有区别吗?还是它们在执行相同的操作? 在创建新的@State变量时,哪个更好用?


我不明白为什么这个被踩了。对我来说,这似乎是一个很好的问题。 - Rob N
2个回答

8
根据该swift-evolution提议

init(initialValue:)已更名为init(wrappedValue:)以匹配属性名称。

从Swift 5.1开始,两者都可用且均未标记为不推荐使用。我仍建议使用init(wrappedValue:)

-2

您不需要直接调用此初始化程序(init(wrappedValue:))。相反,使用@State属性声明一个属性,并提供初始值;例如,@State private var isPlaying: Bool = false。

顺便说一下:https://developer.apple.com/documentation/swiftui/state/3365450-init

我们使用init(initialValue:)来创建具有初始值的状态。

例如:

struct TestView3: View {
    @ObservedObject var data = TestData.shared
    @State private var sheetShowing = false
    var body: some View {
        print("test view3 body, glabel selected = \(data.selected)"); return
        VStack {
            Text("Global").foregroundColor(data.selected ? .red : .gray).onTapGesture {
                self.data.selected.toggle()
            }.padding()
            Button(action: {
                self.sheetShowing = true
                print("test view3, will show test view4")
            }) { Text("Show TestView4") }.padding()
        }.sheet(isPresented: $sheetShowing) { TestView4(selected: self.data.selected) }
    }
}

struct TestView4: View {
    @ObservedObject var data = TestData.shared
    @State private var selected = false
    init(selected: Bool) {
        self._selected = State(initialValue: selected)   // <-------- here
        print("test view4 init, glabel selected = \(data.selected), local selected = \(self.selected)")
    }
    var body: some View {
        print("test view4 body, glabel selected = \(data.selected), local selected = \(selected)"); return
        VStack {
            Text("Local").foregroundColor(selected ? .red : .gray).onTapGesture {
                self.selected.toggle()
                print("test view4, local toggle")
            }.padding()
            Text("Global").foregroundColor(data.selected ? .red : .gray).onTapGesture {
                self.data.selected.toggle()
                print("test view4, global toggle")
            }.padding()
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接