Apple security for developers
Keychain Services in Swift: save, read, update and delete a secret
Working Swift code for the macOS and iOS Keychain: save, read, update and delete a generic password with SecItem, plus the accessibility setting to choose.
Updated 8 October 2026 3 min read
The short answer
Use Keychain Services with the generic-password class: SecItemAdd to save, SecItemCopyMatching to read, SecItemUpdate to change and SecItemDelete to remove. Identify each secret by a service and an account, and set its accessibility to kSecAttrAccessibleWhenUnlockedThisDeviceOnly so it never leaves the device.
Save (or update) a secret
Try an update first and add only if the item isn’t there yet. That makes saving idempotent:
import Foundation
import Security
enum KeychainError: Error { case notFound, unexpected(OSStatus) }
func saveSecret(_ secret: String, service: String, account: String) throws {
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: service,
kSecAttrAccount as String: account,
]
let attributes: [String: Any] = [
kSecValueData as String: Data(secret.utf8),
kSecAttrAccessible as String: kSecAttrAccessibleWhenUnlockedThisDeviceOnly,
]
var status = SecItemUpdate(query as CFDictionary, attributes as CFDictionary)
if status == errSecItemNotFound {
status = SecItemAdd(query.merging(attributes) { $1 } as CFDictionary, nil)
}
guard status == errSecSuccess else { throw KeychainError.unexpected(status) }
}Read it back
func readSecret(service: String, account: String) throws -> String {
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: service,
kSecAttrAccount as String: account,
kSecReturnData as String: true,
kSecMatchLimit as String: kSecMatchLimitOne,
]
var item: CFTypeRef?
let status = SecItemCopyMatching(query as CFDictionary, &item)
if status == errSecItemNotFound { throw KeychainError.notFound }
guard status == errSecSuccess, let data = item as? Data else { throw KeychainError.unexpected(status) }
return String(decoding: data, as: UTF8.self)
}Read at the moment you need the value and don’t cache it in a property that outlives the request.
Delete it
func deleteSecret(service: String, account: String) throws {
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: service,
kSecAttrAccount as String: account,
]
let status = SecItemDelete(query as CFDictionary)
guard status == errSecSuccess || status == errSecItemNotFound else { throw KeychainError.unexpected(status) }
}Choosing the accessibility
Accessibility decides when the item can be read and whether it may move to another device:
kSecAttrAccessibleWhenUnlockedThisDeviceOnly: readable only while the device is unlocked, never restored to another device. The right default for API keys.kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly: for background work that runs while the screen is locked.- Avoid the variants without
ThisDeviceOnlyfor credentials unless you want them to sync.
Going further: require Touch ID
To make the system demand Touch ID before every read, store the item with a SecAccessControl instead of a plain accessibility value. The Touch ID guide shows how.
The safe way to do this
MoltenRock
The encrypted vault for your API keys and AI agents
Your keys sealed by your Mac’s Secure Enclave, handed only to the local agents you approve, never written to a .env file. Free for Mac.
Get MoltenRock, freeQuestions developers ask
What is the difference between kSecAttrService and kSecAttrAccount?
Together they identify a generic password. Use the service for what the secret is for (an API name) and the account for whose it is.
Does SecItemAdd overwrite an existing item?
No. It fails with errSecDuplicateItem. Update first and add on errSecItemNotFound, as in the code above.
Is this the same on iOS?
The API is the same. On macOS you choose between the file-based login keychain and the data-protection keychain; iOS always uses the latter.