Error handling is an essential part of working with the Keychain in Swift. Properly managing errors not only ensures a more robust application but also provides users with clearer feedback when something goes wrong. Here are common patterns and examples for handling errors when interacting with the Keychain in Swift.
// Example of adding a keychain item with error handling
import Security
enum KeychainError: Error {
case unexpectedStatus(OSStatus)
}
func addKeychainItem(service: String, account: String, data: Data) throws {
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: service,
kSecAttrAccount as String: account,
kSecValueData as String: data
]
let status = SecItemAdd(query as CFDictionary, nil)
if status != errSecSuccess {
throw KeychainError.unexpectedStatus(status)
}
}
// Usage
do {
let passwordData = "mySecurePassword".data(using: .utf8)!
try addKeychainItem(service: "com.example.app", account: "user@example.com", data: passwordData)
} catch let error {
print("Error adding to Keychain: \(error)")
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?