Skip to main content
freelanceshack.com

Back to all posts

How to Work With UserDefaults In Swift?

Published on
5 min read
How to Work With UserDefaults In Swift? image

Best Swift Programming Guides to Buy in October 2025

1 Mastering Swift 6: Modern programming techniques for high-performance apps in Swift 6.2

Mastering Swift 6: Modern programming techniques for high-performance apps in Swift 6.2

BUY & SAVE
$44.99 $49.99
Save 10%
Mastering Swift 6: Modern programming techniques for high-performance apps in Swift 6.2
2 Swift Programming: The Big Nerd Ranch Guide (Big Nerd Ranch Guides)

Swift Programming: The Big Nerd Ranch Guide (Big Nerd Ranch Guides)

BUY & SAVE
$44.73
Swift Programming: The Big Nerd Ranch Guide (Big Nerd Ranch Guides)
3 Modern Swift Programming: From Fundamentals to Building Your First Apple Apps

Modern Swift Programming: From Fundamentals to Building Your First Apple Apps

BUY & SAVE
$24.99
Modern Swift Programming: From Fundamentals to Building Your First Apple Apps
4 Learning Swift: Building Apps for macOS, iOS, and Beyond

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

BUY & SAVE
$28.49 $49.99
Save 43%
Learning Swift: Building Apps for macOS, iOS, and Beyond
5 Swift in Depth

Swift in Depth

  • MASTER SWIFT WITH HANDS-ON EXAMPLES AND REAL-WORLD PROJECTS!
  • UNLOCK POWERFUL CODING TECHNIQUES FOR IOS AND MACOS DEVELOPMENT!
  • LEARN SWIFT FAST WITH CLEAR, CONCISE EXPLANATIONS AND TIPS!
BUY & SAVE
$49.99
Swift in Depth
6 Head First Swift: A Learner's Guide to Programming with Swift

Head First Swift: A Learner's Guide to Programming with Swift

BUY & SAVE
$38.93 $79.99
Save 51%
Head First Swift: A Learner's Guide to Programming with Swift
+
ONE MORE?

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.

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.

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.

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.

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.

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.

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:

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:

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:

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.

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.

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.

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:

let encryptionKey = "YourEncryptionKey"

  1. Add an Encryption extension:

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:

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:

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:

// 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.