0

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

  • 1
    Consider that you save an integer value for a random key. I suppose you mean the opposite. – vadian Nov 19 '21 at 18:14
  • i just want to save my random generated string, i'm new to programming so i didn't fully understand your answer( –  Nov 19 '21 at 18:25
  • You want to save random generated string for which key? – Imran0001 Nov 19 '21 at 18:32
  • i think int key? –  Nov 19 '21 at 18:43
  • Suppose your name is "abcd", then you can save "abcd" for the key "name" or anything you want. You must need a key for saving anything in userDefaults. – Imran0001 Nov 19 '21 at 18:44
  • so what's the key in my case? –  Nov 19 '21 at 18:55
  • Anything you want but you need to pass it as a string. Check my answer. Suppose you want to store a book list, then you can set "bookList" as the key. It is so that you can realize what you stored by this key. – Imran0001 Nov 19 '21 at 18:57

1 Answers1

0

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")
        }
    }
Imran0001
  • 580
  • 4
  • 11
  • it says "Instance member 'randomString' cannot be used on type 'ViewController'" –  Nov 19 '21 at 19:26
  • Check here and hope you can solve this simple problem. https://stackoverflow.com/a/34012230/14373360 – Imran0001 Nov 20 '21 at 03:13
  • thank uuu, it helped a lot. but i had to remove "static" will it affect to something? –  Nov 20 '21 at 08:02
  • Welcome. You can get a clear idea about the static variable here https://stackoverflow.com/a/53818259/14373360 then you will know if it affects or not. Happy programming. – Imran0001 Nov 20 '21 at 08:44