How to Work With UserDefaults In Swift?

10 minutes read

UserDefaults is a built-in class in Swift that allows you to store and retrieve small amounts of user-related data. It provides a simple and convenient way to save user preferences, settings, and other application-specific data.


To work with UserDefaults in Swift, you need to follow these steps:

  1. Import the Foundation framework: Before you can use UserDefaults, you need to import the Foundation framework at the top of your Swift file.
1
import Foundation


  1. Save data to UserDefaults: To save data to UserDefaults, you can use the set(_:forKey:) method. The data types supported by UserDefaults include integers, floats, booleans, strings, arrays, dictionaries, and dates.
1
2
3
4
let defaults = UserDefaults.standard
defaults.set(42, forKey: "MyNumber")
defaults.set("John", forKey: "Username")
defaults.set(true, forKey: "IsLoggedIn")


  1. Retrieve data from UserDefaults: To retrieve data from UserDefaults, you can use the object(forKey:) method. Make sure to cast the retrieved value to the appropriate data type.
1
2
3
let number = defaults.object(forKey: "MyNumber") as? Int ?? 0
let username = defaults.object(forKey: "Username") as? String ?? ""
let isLoggedIn = defaults.object(forKey: "IsLoggedIn") as? Bool ?? false


  1. Remove data from UserDefaults: To remove data from UserDefaults, you can use the removeObject(forKey:) method.
1
defaults.removeObject(forKey: "Username")


  1. Synchronize changes: UserDefaults automatically saves changes to disk periodically. However, if you want to ensure that the changes are immediately saved, you can call the synchronize() method.
1
defaults.synchronize()


By using UserDefaults, you can easily save and retrieve user-related data in your Swift applications, making it convenient to handle user preferences and settings.

Best Swift Books to Read in 2024

1
Learning Swift: Building Apps for macOS, iOS, and Beyond

Rating is 5 out of 5

Learning Swift: Building Apps for macOS, iOS, and Beyond

2
Beginning iOS 16 Programming with Swift and SwiftUI: Learn to build a real world iOS app from scratch using Swift and SwiftUI (Mastering iOS Programming and Swift Book 1)

Rating is 4.9 out of 5

Beginning iOS 16 Programming with Swift and SwiftUI: Learn to build a real world iOS app from scratch using Swift and SwiftUI (Mastering iOS Programming and Swift Book 1)

3
iOS 15 Programming Fundamentals with Swift: Swift, Xcode, and Cocoa Basics

Rating is 4.8 out of 5

iOS 15 Programming Fundamentals with Swift: Swift, Xcode, and Cocoa Basics

4
Hello Swift!: iOS app programming for kids and other beginners

Rating is 4.7 out of 5

Hello Swift!: iOS app programming for kids and other beginners

5
iOS Swift Game Development Cookbook: Simple Solutions for Game Development Problems

Rating is 4.6 out of 5

iOS Swift Game Development Cookbook: Simple Solutions for Game Development Problems

6
iOS Development with Swift

Rating is 4.5 out of 5

iOS Development with Swift

7
iOS 16 Programming for Beginners: Kickstart your iOS app development journey with a hands-on guide to Swift 5.7 and Xcode 14, 7th Edition

Rating is 4.4 out of 5

iOS 16 Programming for Beginners: Kickstart your iOS app development journey with a hands-on guide to Swift 5.7 and Xcode 14, 7th Edition

8
Beginning iPhone Development with Swift 5: Exploring the iOS SDK

Rating is 4.3 out of 5

Beginning iPhone Development with Swift 5: Exploring the iOS SDK


How to set a value in UserDefaults in Swift?

To set a value in UserDefaults in Swift, you can use the following steps:

  1. Import the UserDefaults module at the top of your file:
1
import UIKit


  1. Set the value using the set(_:forKey:) method of the UserDefaults class. For example, to set a string value for a key:
1
2
let defaults = UserDefaults.standard
defaults.set("Hello, World!", forKey: "myKey")


  1. Call the synchronize() method to save the changes immediately. Although this step is not necessary in modern versions of Swift, it ensures that the value is saved in older versions:
1
defaults.synchronize()


That's it! The value is now set in the UserDefaults. You can access it later using the same key.


How to retrieve a float value from UserDefaults in Swift?

To retrieve a float value from UserDefaults in Swift, you can follow these steps:

  1. Access the UserDefaults instance using the standard property.
1
let defaults = UserDefaults.standard


  1. Use the float(forKey:) method of UserDefaults to retrieve the float value associated with a specific key. Provide the key you used when setting the value.
1
let floatValue = defaults.float(forKey: "yourFloatKey")


  1. If the specified key does not exist in UserDefaults, the float(forKey:) method will return 0.0 by default. You can check for the existence of the key using the object(forKey:) method and handle the case accordingly.
1
2
3
4
5
6
7
if defaults.object(forKey: "yourFloatKey") != nil {
    let floatValue = defaults.float(forKey: "yourFloatKey")
    // Handle the retrieved float value
}
else {
    // Key does not exist in UserDefaults
}


Make sure to replace "yourFloatKey" with the actual key you used when storing the float value in UserDefaults.


How to encrypt values stored in UserDefaults in Swift?

To encrypt values stored in UserDefaults in Swift, you can follow these steps:

  1. Define an Encryption/Decryption Key:
1
let encryptionKey = "YourEncryptionKey"


  1. Add an Encryption extension:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import Foundation
import CommonCrypto

extension String {
    func encrypt(key: String) throws -> String {
        guard let keyData = key.data(using: .utf8), let messageData = self.data(using: .utf8) else {
            throw NSError(domain: "EncryptionError", code: 0, userInfo: nil)
        }

        let cryptLength = messageData.count + kCCBlockSizeAES128
        var cryptData = Data(count: cryptLength)

        let keyLength = size_t(kCCKeySizeAES128)
        let options = CCOptions(kCCOptionPKCS7Padding)

        var numBytesEncrypted: size_t = 0

        let status = cryptData.withUnsafeMutableBytes { cryptBytes in
            keyData.withUnsafeBytes { keyBytes in
                messageData.withUnsafeBytes { dataBytes in
                    CCCrypt(CCOperation(kCCEncrypt),
                            UInt32(kCCAlgorithmAES128),
                            options,
                            keyBytes, keyLength,
                            nil,
                            dataBytes, messageData.count,
                            cryptBytes, cryptLength,
                            &numBytesEncrypted)
                }
            }
        }

        if status == CCCryptorStatus(kCCSuccess) {
            cryptData.count = numBytesEncrypted
            return cryptData.base64EncodedString()
        } else {
            throw NSError(domain: "EncryptionError", code: Int(status), userInfo: nil)
        }
    }

    func decrypt(key: String) throws -> String {
        guard let keyData = key.data(using: .utf8), let messageData = Data(base64Encoded: self) else {
            throw NSError(domain: "DecryptionError", code: 0, userInfo: nil)
        }

        let cryptLength = messageData.count + kCCBlockSizeAES128
        var cryptData = Data(count: cryptLength)

        let keyLength = size_t(kCCKeySizeAES128)
        let options = CCOptions(kCCOptionPKCS7Padding)

        var numBytesDecrypted: size_t = 0

        let status = cryptData.withUnsafeMutableBytes { cryptBytes in
            keyData.withUnsafeBytes { keyBytes in
                messageData.withUnsafeBytes { dataBytes in
                    CCCrypt(CCOperation(kCCDecrypt),
                            UInt32(kCCAlgorithmAES128),
                            options,
                            keyBytes, keyLength,
                            nil,
                            dataBytes, messageData.count,
                            cryptBytes, cryptLength,
                            &numBytesDecrypted)
                }
            }
        }

        if status == CCCryptorStatus(kCCSuccess) {
            cryptData.count = numBytesDecrypted
            return String(data: cryptData, encoding: .utf8) ?? ""
        } else {
            throw NSError(domain: "DecryptionError", code: Int(status), userInfo: nil)
        }
    }
}


  1. Encrypt and store the value in UserDefaults:
1
2
3
4
5
6
7
let valueToEncrypt = "Value to Encrypt"
do {
    let encryptedValue = try valueToEncrypt.encrypt(key: encryptionKey)
    UserDefaults.standard.set(encryptedValue, forKey: "EncryptedValue")
} catch {
    print("Encryption Error: \(error)")
}


  1. Decrypt the value from UserDefaults:
1
2
3
4
5
6
7
8
if let encryptedValue = UserDefaults.standard.string(forKey: "EncryptedValue") {
    do {
        let decryptedValue = try encryptedValue.decrypt(key: encryptionKey)
        print("Decrypted Value: \(decryptedValue)")
    } catch {
        print("Decryption Error: \(error)")
    }
}


Make sure to replace "YourEncryptionKey" with your desired encryption key.


How to set a default value in UserDefaults in Swift?

To set a default value in UserDefaults in Swift, you can use the register(defaults:) method of the UserDefaults class. Here's an example:

1
2
3
4
5
// Get the standard UserDefaults instance
let defaults = UserDefaults.standard

// Set the default value for a specific key
defaults.register(defaults: ["myKey": "defaultValue"])


In this example, the key "myKey" is set to a default value of "defaultValue". If this key has not been previously set by the user or programmatically, it will have the default value.


You can set multiple default values by providing a dictionary to the register(defaults:) method. Each key-value pair in the dictionary represents a default value for a specific key.


Remember to call register(defaults:) before accessing any values in the UserDefaults, preferably during app launch or in the application(_:didFinishLaunchingWithOptions:) method in your AppDelegate file.

Twitter LinkedIn Telegram Whatsapp

Related Posts:

Codable is a protocol introduced in Swift 4 that allows for easy encoding and decoding of Swift types to and from external representations, such as JSON. It provides a convenient way to handle JSON serialization and deserialization without having to manually w...
JSON is a popular format used for exchanging data between a client and a server. In Swift, handling JSON parsing involves converting JSON data into native data types that can be easily manipulated within the app. Here's how JSON parsing can be handled in S...
Option sets are an essential feature in Swift that allows you to define and work with custom sets of related options or flags. They provide a flexible and type-safe way to manipulate multiple options simultaneously.To work with option sets in Swift, you need t...