Home > Blockchain >  Save random alphanumeric string in Userdefaults
Save random alphanumeric string in Userdefaults

Time:11-20

i'm new to swift and i have a problem. How i can save randomly generated for each user alphanumeric string in user defaults?

    func randomString(of length: Int) -> String {
        let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
        var s = ""
        for _ in 0 ..< length {
            s.append(letters.randomElement()!)
        }
        return s
    }
   
    static var keyS: Bool {
        get {
            return ((UserDefaults.standard.integer(forKey: randomString(of: 16)) != 0))
        }
        set {
            UserDefaults.standard.set(1, forKey: randomString(of: 16))
        }
    }

i tried this, but it didn't work. hope somebody can help me

CodePudding user response:

Here "1" is your key for storing the random string. You can set it anything you want. Try this-

func randomString(of length: Int) -> String {
        let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
        var s = ""
        for _ in 0 ..< length {
            s.append(letters.randomElement()!)
        }
        return s
    }
   
    static var keyS: Bool {
        get {
            return ((UserDefaults.standard.integer(forKey: "1") != 0))
        }
        set {
            UserDefaults.standard.set(randomString(of: 16), forKey: "1")
        }
    }
  • Related