0
votes

I'm trying to create a text field where the text within becomes a var and a user default which will be displayed all the time.

I have tried making it equal to a variable where I have set it within the section. But I really have no idea what I'm doing.

@State private var Name = UserDefaults.standard.string(forKey: "name")

Section{
  TextField("Name", text: $Name)
  UserDefaults.standard.set($Name, forKey: "name")
}
1
@State private var Name = UserDefaults.standard.string(forKey: "name") { didSet{ UserDefaults.standard.set(Name, forKey: "name") } } - fakiho

1 Answers

-1
votes

struct Defaults {

static let (nameKey, addressKey) = ("name", "address")
static let userSessionKey = "com.save.usersession"
private static let userDefault = UserDefaults.standard

/**
   - Description - It's using for the passing and fetching
                user values from the UserDefaults.
 */
struct UserDetails {
    let name: String
    let address: String

    init(_ json: [String: String]) {
        self.name = json[nameKey] ?? ""
        self.address = json[addressKey] ?? ""
    }
}

/**
 - Description - Saving user details
 - Inputs - name `String` & address `String`
 */
static func save(_ name: String, address: String){
    userDefault.set([nameKey: name, addressKey: address], 
                    forKey: userSessionKey)
}

/**
 - Description - Fetching Values via Model `UserDetails` you can use it based on your uses.
 - Output - `UserDetails` model
 */
static func getNameAndAddress()-> UserDetails {
    return UserDetails((userDefault.value(forKey: userSessionKey) as? [String: String]) ?? [:])
}

/**
    - Description - Clearing user details for the user key `com.save.usersession`
 */
static func clearUserData(){
    userDefault.removeObject(forKey: userSessionKey)
}

}