---
title: "#75: Locksmith 🔐"
url: https://littlebitesofcocoa.com/75-locksmith
author: Jake Marsh
date: 2015-09-04
published: 2015-09-04
topics: ["Libraries","Security"]
description: "Locksmith is a library from Matthew Palmer that really improves how we can interact with the Keychain. Let's look at the basics: That's just the beginning..."
---

# #75: Locksmith 🔐

By Jake Marsh, September 4, 2015. HTML: https://littlebitesofcocoa.com/75-locksmith

[Locksmith](http://git.io/locksmith) is a library from [Matthew Palmer](https://github.com/matthewpalmer) that really improves how we can interact with the **Keychain**. Let's look at the basics:

## Reading Data

``` swift
let dictionary = Locksmith.loadDataForUserAccount("kyloren")
```

## Writing Data

``` swift
do {
  try Locksmith.saveData(
    ["saberColor": "#FF0000"],
    forUserAccount: "kyloren"
  )
} catch { }
```

## Updating Data

``` swift
do {
  try Locksmith.updateData(
    ["saberColor": "#30FF00"],
    forUserAccount: "kyloren"
  )
} catch { }
```

## Deleting Data

``` swift
do {
  try Locksmith.deleteDataForUserAccount("kyloren")
} catch { }
```

That's just the beginning though. **Locksmith** supports almost _every_ feature **Keychain** has to offer. It also embraces **protocols**, and **protocol extensions**. Let's look at an example of how to improve our own **types**, making them easier to store in the **Keychain**.

Let's say we have a simple **struct** in our app to represent user **accounts**. We'll implement a couple of **protocols** from **Locksmith** on it: 

``` swift
struct JediTempleAccount: GenericPasswordSecureStorable,
  CreateableSecureStorable, ReadableSecureStorable,
  DeleteableSecureStorable {

  let username: String, password: String

  let service = "jedi-temple"
  var account: String { return username }
  var data: [String: AnyObject] { return ["password": password] }
}
```

Now we can work with **accounts** and the **Keychain** like this:

``` swift
let account = JediTempleAccount(username: "kyloren", password: "yaysith")

do { try account.createInSecureStore() } catch { } // save
let result = account.readFromSecureStore() // retrieve
do { try account.deleteFromSecureStore() } catch { } // delete
```

More info about **Locksmith** can be found at [git.io/locksmith](http://git.io/locksmith)
