Sarabjit
Sarabjit

Reputation: 149

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. 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 {...}

Upvotes: 0

Views: 763

Answers (2)

iPatel
iPatel

Reputation: 47049

You should use UserDefaults for save your random value. 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.

Ex.

You get random value 1234 in stranger then you should first check you already set the value or not?

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")")

Upvotes: 3

Lee
Lee

Reputation: 10603

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.

Register your default properties. In AppDelegate.didFinishingLaunching may be a good place

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.

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. Demo purposes only

Upvotes: 0

Related Questions