简体   繁体   English

快速使变量值恒定

[英]Making a variable value constant in swift

I'm very new to coding in swift, so I barely know any of the syntaxes. 我对快速编码非常陌生,因此我几乎不了解任何语法。 I am defining a variable in view controller and assigning it a random 4 digit value. 我在视图控制器中定义一个变量,并为其分配一个随机的4位数字值。 I want to assign this value only once, when the app is installed/updated, and not every time the user opens the app. 我只想在安装/更新应用程序时分配一次该值,而不是在用户每次打开应用程序时都分配一次。 Help me out if any of you know a fix for this. 如果有人知道此修复程序,请帮助我。 The following is my current code 以下是我当前的代码

import UIKit
let stranger = String(arc4random_uniform(10000))

class ViewController: UIViewController {...}

You should use UserDefaults for save your random value. 您应该使用UserDefaults保存您的随机值。 When you open you app first time then you will be got some random value in stranger . 第一次打开应用程序时,您会在陌生人中得到一些随机值。 Add those value in UserDefaults with specific key and you can access value by use of key that you set in UserDefault . 使用特定密钥将这些值添加到UserDefaults ,然后可以使用在UserDefault设置的密钥来访问值。

Ex. 防爆。

You get random value 1234 in stranger then you should first check you already set the value or not? 您在陌生人中获得随机值1234 ,然后应首先检查是否已设置该值?

if UserDefaults.standard.object(forKey: "keyRandom") == nil { // If value already set then you do not need to reset
  UserDefaults.standard.set(stranger, forKey: "keyRandom")
}

And if you want to access value you can get it by 如果您想获得价值,可以通过

print("\(UserDefaults.standard.object(forKey: "keyRandom") ?? "not Found")")

You need to store the data in a persistent data store if you want to persist between launches. 如果要在两次启动之间保持持久性,则需要将数据存储在持久性数据存储中。 UserDefaults is a simple solution, and you can use the registerDefaults method to seed it. UserDefaults是一个简单的解决方案,您可以使用registerDefaults方法为其添加种子。

Register your default properties. 注册您的默认属性。 In AppDelegate.didFinishingLaunching may be a good place AppDelegate.didFinishingLaunching可能是一个好地方

UserDefaults.standard.register(defaults: [
            "MyKey" : String(arc4random_uniform(10000))
        ])

Pull out the value: 拉出值:

let stranger = UserDefaults.standard.string(forKey: "MyKey")

If you don't want to register the defaults on app start, or need to change it, then you can also set the property when you first need it, using an if let check to see if it already exists, and if not, set it. 如果您不想在应用启动时注册默认值或需要更改默认值,则还可以在首次使用该属性时设置该属性,使用if let检查是否已存在该属性,如果不存在,请进行设置它。

func getStranger() -> String {
    if let v = UserDefaults.standard.string(forKey: "MyKey") {
        return v
    } else {
        let rand = String(arc4random_uniform(10000))
        UserDefaults.standard.set(rand, forKey:"MyKey")
        return rand
    }
}

Note: Code written in SO answer box, not tested and may contain syntax errors. 注意:在SO答案框中编写的代码未经测试,可能包含语法错误。 Demo purposes only 仅用于演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM