Skip to content

Instantly share code, notes, and snippets.

@sajjadsarkoobi
Created September 3, 2018 08:52
Show Gist options
  • Save sajjadsarkoobi/15f7fbaaf0dfb9be193d5f480931bd12 to your computer and use it in GitHub Desktop.
Save sajjadsarkoobi/15f7fbaaf0dfb9be193d5f480931bd12 to your computer and use it in GitHub Desktop.
Medium - UserDefaults
//
// userHolder.swift
// Medium_userDefaults
//
// Created by Sajjad Sarkoobi on 9/3/18.
// Copyright © 2018 sarkoobi. All rights reserved.
//
import Foundation
var UserHolder = userData()
struct userData {
private let defaultStorage = UserDefaults.standard
enum UserDefaultsKeys:String {
case userToken
case name
case age
case avatarLink
}
//retriving data from Default Storage
private func getFromdefaultStorage(key: UserDefaultsKeys ) -> String {
if let response = defaultStorage.value(forKey: key.rawValue ) {
return response as! String
} else {
return ""
}
}
// Putting data in Default Storage
private func saveTodefaultStorage(key:UserDefaultsKeys, val:String) {
defaultStorage.set(val, forKey: key.rawValue)
}
//Delete All User Data
func deleteAllData(){
let domain = Bundle.main.bundleIdentifier!
UserDefaults.standard.removePersistentDomain(forName: domain)
UserDefaults.standard.synchronize()
}
//user Token
var userToken : String {
get {
return getFromdefaultStorage(key: .userToken)
}
set(newValue){
saveTodefaultStorage(key: UserDefaultsKeys.userToken, val: newValue)
}
}
//user name
var name : String {
get {
return getFromdefaultStorage(key: .name)
}
set(newValue){
saveTodefaultStorage(key: UserDefaultsKeys.name, val: newValue)
}
}
//user age
var age : String {
get {
return getFromdefaultStorage(key: .age)
}
set(newValue){
saveTodefaultStorage(key: UserDefaultsKeys.age, val: newValue)
}
}
//user avatar
var avatarLink : String {
get {
return getFromdefaultStorage(key: .avatarLink)
}
set(newValue){
saveTodefaultStorage(key: UserDefaultsKeys.avatarLink, val: newValue)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment