Skip to content

Instantly share code, notes, and snippets.

@KalpeshTalkar
Last active December 7, 2018 20:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save KalpeshTalkar/4c935471e81cd94b0468cb248a515951 to your computer and use it in GitHub Desktop.
Save KalpeshTalkar/4c935471e81cd94b0468cb248a515951 to your computer and use it in GitHub Desktop.
LocalStorage is an abstraction over the UserDefaults. The class is written in Swift 3
// Copyright © 2017 Kalpesh Talkar. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// For support: https://gist.github.com/KalpeshTalkar/4c935471e81cd94b0468cb248a515951
//
/// LocalStorage is an abstraction over the UserDefaults.
/// - Save data locally
/// - Get local saved data
/// - Get local saved data in preferred data type
class LocalStorage {
/// Save data locally
///
/// - Parameters:
/// - value: data to be stored
/// - key: key
class func set(value: Any, for key: String) {
UserDefaults.standard.set(value, forKey: key)
}
/// Get locally saved data if exists
///
/// - Parameter key: key against which the data is stored
/// - Returns: data stored against the key, nil of no data present
class func get(for key: String) -> Any? {
return UserDefaults.value(forKey: key)
}
/// Get locally saved data with specific data type if exists
///
/// - Parameters:
/// - key: key against which the data is stored
/// - type: data type of the data
/// - Returns: data with the specified data type or nil of no data present/invalid data type
class func get<T>(for key: String, of type: T.Type) -> T? {
return UserDefaults.value(forKey: key) as? T
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment