Last active
February 1, 2020 16:38
-
-
Save ANSCoder/d7faaa8d7211663ef797ce0207e11688 to your computer and use it in GitHub Desktop.
UserDefaults example for save and get data in Swift 4.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment