SwiftyChain is a Swift 6.3 keychain wrapper for Apple platforms. It provides a typed Keychain actor for async-safe access and an @KeychainStorage property wrapper for simple optional values.
import SwiftyChain
let tokenKey = KeychainKey<String>(service: "com.example.app", account: "auth_token")
try await Keychain.shared.upsert("secret", for: tokenKey)
let token = try await Keychain.shared.loadIfPresent(key: tokenKey)@KeychainStorage("auth_token", service: "com.example.app")
var authToken: String?account and service are the required initializer parameters. The full
initializer is:
@KeychainStorage(
"auth_token",
service: "com.example.app",
accessGroup: nil,
accessibility: .whenUnlocked,
isSynchronizable: false,
defaultValue: nil
)
var authToken: String?Use the optional arguments only when needed:
accessGroupto share credentials with another app target or extensionaccessibilityto control when the item can be readisSynchronizableto opt into iCloud Keychain syncdefaultValueto return a fallback when nothing is stored yet
The Swift macros (@KeychainItem, @KeychainScope, #keychainKey) are included by default. Two optional traits gate specialised features:
SwiftyChain ships a separate SwiftyChainTesting product for downstream tests.
import SwiftyChain
import SwiftyChainTesting
let keychain: any KeychainProtocol = InMemoryKeychain()
let tokenKey = KeychainKey<String>(service: "com.example.app", account: "auth_token")
try await keychain.upsert("secret", for: tokenKey)
#expect(try await keychain.load(key: tokenKey) == "secret")import SwiftyChain
import SwiftyChainTesting
let backend = InMemoryKeychainBackend()
let storage = KeychainStorage<String>(
"auth_token",
service: "com.example.app",
backend: backend
)
storage.wrappedValue = "secret"
#expect(storage.wrappedValue == "secret")xcrun swift build -Xswiftc -warnings-as-errors
xcrun swift test -Xswiftc -warnings-as-errors --enable-code-coverage
xcrun swift-format lint --recursive --strict Sources Tests Package.swiftOptional features are guarded by traits. Enable them explicitly when building or testing:
xcrun swift test --traits "observation,cryptography"Set SWIFTYCHAIN_RUN_KEYCHAIN_INTEGRATION=1 to opt into the suite that exercises the real Apple keychain.