在Swift [UI]中疯狂使用UserDefaults [英] Going crazy with UserDefaults in Swift[UI]

查看:254
本文介绍了在Swift [UI]中疯狂使用UserDefaults的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将自己引入Swift和SwiftUI的过程中,我发现从UIKit进行迁移的过程相当困难. 即使试图理解我在网络上找到的许多教程,目前也被UserDefaults踩死了.

Launching myself into Swift and SwiftUI, I find the process of migrating from UIKit quite hard. Presently stomped by UserDefaults, even after trying to make sense of the many tutorials I found on the web.

请告诉我我在做什么错: 非常简单的代码:

Please tell me what I'm doing wrong here : VERY simple code to :

  1. 将bool值注册到UserDefault,
  2. 在文本中显示该布尔值!

没有比这更简单的了. 但是我无法使其正常工作,因为对UserDefaults的调用会引发以下错误消息:

Doesn't get any simpler than that. But I can't get it to work, as the call to UserDefaults throws this error message :

实例方法"appendInterpolation"要求布尔"符合"_FormatSpecifiable"

Instance method 'appendInterpolation' requires that 'Bool' conform to '_FormatSpecifiable'

我的应用"是具有以下2个更改的默认单视图应用:

My "app" is the default single view app with the 2 following changes :

1-在AppDelegate中,我注册了bool:

1- In AppDelegate, I register my bool :

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.

    UserDefaults.standard.register(defaults: [
    "MyBool 1": true
    ])


    return true
}

2-在ContentView中,我尝试显示它(在ContentContentView结构中:View):

2- in ContentView, I try to display it (inside struct ContentView: View) :

let defaults = UserDefaults.standard

var body: some View {
    Text("The BOOL 1 value is : Bool 1 = \(defaults.bool(forKey: "MyBool 1"))")
}

有什么想法吗?

谢谢

推荐答案

您的问题是Text(...)初始化程序使用LocalizedStringKey而不是String,该初始化程序在其字符串插值中支持的类型与普通字符串不同(显然不包含Bool.

Your issue is that the Text(...) initializer takes a LocalizedStringKey rather than a String which supports different types in its string interpolation than plain strings do (which does not include Bool apparently).

有两种方法可以解决此问题.

There's a couple ways you can work around this.

您可以使用采用StringText初始化程序,并按原样显示它而无需尝试进行任何本地化:

You could use the Text initializer that takes a String and just displays it verbatim without attempting to do any localization:

var body: some View {
    Text(verbatim: "The BOOL 1 value is : Bool 1 = \(defaults.bool(forKey: "MyBool 1"))")
}

或者,您可以扩展LocalizedStringKey.StringInterpolation以支持bool,然后您的原始代码应该可以工作:

Alternatively, you could extend LocalizedStringKey.StringInterpolation to support bools and then your original code should work:

extension LocalizedStringKey.StringInterpolation {
    mutating func appendInterpolation(_ value: Bool) {
        appendInterpolation(String(value))
    }
}

这篇关于在Swift [UI]中疯狂使用UserDefaults的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆