当变量首次用于自己的初始化时,如何清除“变量...在初始化之前使用”错误?

问题描述 投票:0回答:0

背景: 我正在使用核心数据来处理我的应用程序用户设置的持久存储。我的设置之一是

Color
值,我将其转换为 RGB 值,存储为由 Core Data 管理的
InitialsImageColor
类型对象的属性。在
Color
视图中使用
ColorPicker
选择
Form

问题: 我有一个变量

imageColor
,我正在视图的
init()
声明中初始化它。编译器抛出错误“初始化前使用的变量‘self.imageColor’”5 次。为了清楚起见,这是带有注释的相关代码部分:

struct SettingsView: View {
    // Access the managed object context for saving changes to Core Data
    @Environment(\.managedObjectContext) var moc

    // Load stored InitialsImageColor objects from Core Data
    @FetchRequest(sortDescriptors: []) var colorSetting: FetchedResults<InitialsImageColor>
    
    // A Color variable for the ColorPicker View to bind to
    @State private var imageColor: Color

    // A String variable for the Form View's .searchable modifier to bind to
    @State private var searchText: String = ""
    
    // A Bool variable to change to make the .sheet containing SettingsView to disappear
    @Binding var showSettings: Bool
    
    // An initializer to set the starting value for the ColorPicker View to use
    init() {
        imageColor = Color(                        // This line throws error
            red: colorSetting.first?.r ?? 255.0,   // This line throws error
            green: colorSetting.first?.g ?? 255.0, // This line throws error
            blue: colorSetting.first?.b ?? 255.0,  // This line throws error
            opacity: colorSetting.first?.a ?? 1.0  // This line throws error
        )
    }
  1. 这怎么可能?变量的第一次使用是在初始化程序本身中。这个错误不应该发生。
  2. 我该怎么做才能解决它?

最初,我试图在它的声明中初始化

imageColor
,但是当然这没有用,因为它使用另一个变量来得出它的值并且范围在视图的
body
之外。我把它放在
init()
声明中来解决那个问题,然后就发生了。

swift swiftui scope variable-assignment
© www.soinside.com 2019 - 2024. All rights reserved.