Skip to content

maniramezan/SwiftyChain

Repository files navigation

SwiftyChain

CI Docs Swift Platforms SPM License

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.

Quick Start

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:

  • accessGroup to share credentials with another app target or extension
  • accessibility to control when the item can be read
  • isSynchronizable to opt into iCloud Keychain sync
  • defaultValue to return a fallback when nothing is stored yet

Traits

The Swift macros (@KeychainItem, @KeychainScope, #keychainKey) are included by default. Two optional traits gate specialised features:

Testing

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")

Development

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

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

About

Modern Swift wrapper over Keychain API

Resources

License

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages