Based on a blog post I wrote on Sharing tokens between iOS, macOS and watchOS app using the iCloud KeyChain which is I am sure based on something else.

import os
import Foundation

class KeyStore {
    func store(name: String, token : String) {
        let data = token.data(using: .utf8)!
        let addquery: [String: Any] = [kSecClass as String: kSecClassGenericPassword as String,
                                       kSecAttrAccount as String: name,
                                       kSecValueData as String: data
        ]
        SecItemDelete(addquery as CFDictionary)
        let status : OSStatus = SecItemAdd(addquery as CFDictionary, nil)
        guard status == errSecSuccess else {
            os_log("store: whoops")
            return
        }
    }
    
    func clear(name: String) {
        let addquery: [String: Any] = [kSecClass as String: kSecClassGenericPassword as String,
                                       kSecAttrAccount as String: name
        ]
        SecItemDelete(addquery as CFDictionary)
    }
    
    func retrieve(name: String) -> String? {
        let getquery: [String: Any] = [kSecClass as String: kSecClassGenericPassword,
                                       kSecAttrAccount as String: name,
                                       kSecReturnData as String: kCFBooleanTrue!,
                                       kSecMatchLimit as String : kSecMatchLimitOne
        ]
        
        var item: CFTypeRef?
        let status = SecItemCopyMatching(getquery as CFDictionary, &item)
        guard status == errSecSuccess else {
            os_log("keyStore.retrieve SecItemCopyMatching error \(status)")
            return nil
        }
        
        guard let data = item as? Data? else {
            os_log("keyStore.retrieve not data")
            return nil
        }
        
        return String(data: data!, encoding: String.Encoding.utf8)
    }
    
}