Background:我正在使用核心数据来处理我的应用程序的用户设置的持久存储.我的其中一个设置是Color
值,我正在将其转换为存储为由Core Data管理的InitialsImageColor
类型对象的属性的RGB值.在Form
视图中使用ColorPicker
来 Select Color
.
Problem:我有一个变量imageColor
,我正在视图的init()
声明中初始化该变量.编译器抛出一个错误,说"变量‘self.ImageColor’在被初始化之前使用"103.为了清楚起见,以下是相关代码部分及其注释:
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
)
}
- 这怎么可能呢?变量的第一次使用是在初始化式本身中.这种错误不应该发生.
- 我该怎么做才能修复它?
最初,我试图在它的声明中初始化imageColor
,但当然不起作用,因为它使用另一个变量来得出它的值,并且作用域在视图的body
之外.我把它放在init()
号声明中来解决这个问题,然后就发生了这件事.