How to save local data in Swift?

Posted by Wei Xia on May 1, 2017 | Hits:


I would like to save local data in my app, and need to use it sometime. The data could be a response from server.

The application is a swift-build application.


In Swift 3, we can use UserDefaults to handle local data. Below is the example:

// Setting

let defaults = UserDefaults.standard
defaults.set("One", forKey: defaultsKeys.keyOne)
defaults.set("Two", forKey: defaultsKeys.keyTwo)

// Getting

let defaults = UserDefaults.standard
if let stringOne = defaults.string(forKey: defaultsKeys.keyOne) {
    print(stringOne) // One
if let stringTwo = defaults.string(forKey: defaultsKeys.keyTwo) {
    print(stringTwo) // Two


This is the end of post