swift - 当变量首次用于其自身初始化时,如何清除 "Variable ... used before being initialized"错误?

标签 swift swiftui scope variable-assignment

背景:我正在使用 Core Data 来处理应用程序用户设置的持久存储。我的设置之一是 Color 值,我将其转换为 RGB 值,存储为由 Core Data 管理的 InitialsImageColor 类型对象的属性。使用 Form View 中的 ColorPicker 选择 Color

问题:我有一个变量imageColor,正在 View 的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 ,但这当然不起作用,因为它使用另一个变量来得出其值,并且范围超出了 View 的主体。我将它放在 init() 声明中来解决该问题,然后就发生了这种情况。

最佳答案

您的代码存在一些问题。首先,imageColor 有一个 @State 属性包装器,这意味着您实际上想要像这样初始化它:

_imageColor = State(initialValue: Color(red: 1, green: 1, blue: 1) 

不过,您可以轻松地将其写在声明中:

// A Color variable for the ColorPicker View to bind to
@State private var imageColor = Color(red: 1, green: 1, blue: 1)

因为第二个问题是您期望在 init 期间发生获取请求。事实并非如此。您可以而且应该预期 SwiftUI View 会在您无法控制的情况下多次初始化和销毁​​。考虑到这一理念,您会发现在初始化时执行获取请求是没有意义的。它将在 View 的 body 被求值时执行。

更好的解决方案可能是将颜色定义为自定义绑定(bind),而不是单独的状态变量,然后您可以将其传递给另一个 View :

private var imageColor: Binding<Color> {
    Binding<Color>(
        get: { 
            Color(                        
                red: colorSetting.first?.r ?? 255.0, 
                green: colorSetting.first?.g ?? 255.0,
                blue: colorSetting.first?.b ?? 255.0, 
                opacity: colorSetting.first?.a ?? 1.0 
            )
        },
        set: {
            // Write back to your data object
        }
    )
}

(我刚刚从问题中复制了您的 255 个值)

关于swift - 当变量首次用于其自身初始化时,如何清除 "Variable ... used before being initialized"错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75581597/

相关文章:

swift - 是否可以在 SwiftUI 中使用带有自定义字体的动态字体大小?

ios - 订阅对@Published 的更改

javascript - 是否可以在 JavaScript 中调用另一个函数中本地定义的函数?

language-design - 为什么在 swift 中没有存储类的类型属性?

swift - 无法在 gCloud 中部署 Swift Vapor 应用程序

ios - NSFetch请求 : Return dictionary with nested arrays of dictionaries

swift - 当用户在 UItextfields 中快速输入时如何验证和更新模型

ios - swiftui BlendMode 与草图组合模式的差异不匹配

java - 当前线程中不存在具有范围类型注释 @RequestScoped 的 WebBeans 上下文

android - 如何在用户停止查看应用程序 Activity 后停止服务运行。安卓