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


How to Make a Freaking iPhone App - iOS 10 and Swift 3
icon icon


iOS 10 & Swift 3: From Beginner to Paid Professional
icon


The Complete iOS 10 Developer Course - Build 21 Apps
icon


Swift 3 - Learn to Code with Apple's New Language
icon icon


Learn How to Build Mobile Apps for iOS with Swift, PHP and MySQL
icon icon

Follow me on one of your favourite social networks to learn about new video tutorials and code examples:

Twitter: @SwiftVideoBlog
Google Plus: https://plus.google.com/+SergeyKargopolov/posts
Facebook: Swift Developer Blog on Facebook