本文介绍了@AppStorage 变量上的“调用初始化程序时没有完全匹配"错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到以下错误:在我的 变量如下:

I'm getting the following error: No exact matches in call to initializer on my @AppStorage variable below:

Model.swift

class UserSettings: ObservableObject {
    @AppStorage("minAge") var minAge: Float = UserDefaults.standard.float(forKey: "minAge") 

此变量旨在绑定到下面的 Slider 值.

This variable is meant to bind to a Slider value below.

Settings.swift

import SwiftUI
struct Settings: View {
    let auth: UserAuth
    init(auth: UserAuth) {
        self.auth = auth
    }
    @State var minAge = UserSettings().minAge
    let settings = UserSettings()

    var body: some View {
            VStack {
                NavigationView {
                    Form {
                        Section {
                        Text("Min age")
                        Slider(value: $minAge, in: 18...99, step: 1, label: {Text("Label")})
                            .onReceive([self.minAge].publisher.first()) { (value) in
                                UserDefaults.standard.set(self.minAge, forKey: "minAge")
                            }
                        Text(String(Int(minAge)))
                        }

知道问题出在哪里吗?

推荐答案

你不需要中间状态和 UserDefaults,因为你可以直接绑定到 AppStorage 值和它默认使用 UserDefaults.standard.您还需要使用与 Slider 相同的类型,即 Double.

You don't need intermediate state and UserDefaults, because you can bind directly to AppStorage value and it is by default uses UserDefaults.standard. Also you need to use same types with Slider which is Double.

所以,这是一个最小的演示解决方案.使用 Xcode 12 测试.

So, here is a minimal demo solution. Tested with Xcode 12.

struct Settings: View {
    @AppStorage("minAge") var minAge: Double = 18

    var body: some View {
        VStack {
            NavigationView {
                Form {
                    Section {
                        Text("Min age")
                        Slider(value: $minAge, in: 18...99, step: 1, label: {Text("Label")})
                        Text(String(Int(minAge)))
                    }
                }
            }
        }
    }
}

这篇关于@AppStorage 变量上的“调用初始化程序时没有完全匹配"错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 23:00