NSUserDefaults example in Swift

This code example demonstrates how to write and read from NSUserDefaults in Swift. The code example below will cover how to:

  • Create a global instance of NSUserDefaults
  • Write and read the following data types from NSUserDefaults:
    • Integer
    • Boolean
    • Double
    • Objects like String, Date and Array of elements

If you are interested in video lessons on how to write Unit tests and UI tests to test your Swift mobile app, check out this page: Unit Testing Swift Mobile App

Using NSUserDefaults in Swift. Code Example.

// Create a global instance of NSUserDefaults class
 let defaults = UserDefaults.standard
 // Storing Values of different times
 defaults.set(15, forKey: "weight")
 defaults.set(true, forKey: "isActive")
 defaults.set(25.8, forKey: "distance")
 defaults.set("Sergey", forKey: "firstName")
 defaults.set(NSDate(), forKey: "currentDate")
 let friendsNames = ["Bill", "John"]
 defaults.set(friendsNames, forKey: "friendsNames")
 // Reading from NSUserDefaults.
 let weightValue = defaults.integer(forKey: "weight")
 print("weight value = \(weightValue)")
 let isUserActive = defaults.bool(forKey: "isActive")
 print("isUserActive value = \(isUserActive)")
 let distanceValue = defaults.double(forKey: "distance")
 print("distance value = \(distanceValue)")
 let firstNameValue = defaults.object(forKey: "firstName") as! String
 print("First Name value = \(firstNameValue)")
 let currentDateValue = defaults.object(forKey: "currentDate") as! NSDate
 print("Current date value = \(currentDateValue)")
 let friendsNamesArray = defaults.object(forKey: "friendsNames") as? [String] ?? [String]()
 print("Friends names Array count \(friendsNamesArray.count)")
 print("First element in array \(friendsNamesArray[0])")

For more Swift code examples and tutorials, please check the Swift Code Examples page on this website.

Leave a Reply

Your email address will not be published.