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

 

  
  
       // 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])")

Watch this video tutorial to learn how to create UIActivityIndicatorView using Xcode and Main Storyboard.

Swift UIActivityIndicatorView Example 1. Using storyboard.


Learn iOS Development with these Video Courses

The Complete iOS 11 & Swift Developer Course - Build 20 Apps

Use Xcode 9 & Swift 4 to make real apps like Uber and Instagram, with CoreML & ARKit. Includes AWS Credit and much more. Preview this video course. icon

How to Make a Freaking iPhone App - iOS 11 and Swift 4

iPhone App Development from scratch. Learn how to make iOS apps using Xcode 9. The Basics Include Pokemon Go & Snapchat. Learn to build iOS Apps with Xcode 9 and Swift 4. How to Make a Freaking iPhone App - iOS 11 and Swift 4 icon

iOS 11 and Xcode 9 - Complete Swift 4 & Objective-C Course

A Complete iOS 11 and Xcode 9 Course with Swift 4 & Objective-C. Preview this video course. iOS 11 and Xcode 9 - Complete Swift 4 & Objective-C Course icon