Swift: Permanent Data Storage

In this tutorial, we will learn how to save permanently some data in our application.

For data to be saved permanently in our application, we will need to use the “UserDefaults” command.

Save a String permanently

Let’s save the name “Jack” as a the username for our last visitor in our application. To do that, we will need to proceed as follows:

UserDefaults.standard().set(“Jack”, forKey: “username”)

This will save the name Jack permanently in our application. To call it back and use it, we will need to do:

let usernameobject = UserDefaults.standard().object(forKey: “username”)

if let username = username object as? String {

print(username) // this will output Jack


So we will first create an optional called “usernameobject” that will use search for the data which is linked to the key “username”.

If it finds some data, then it will be given to the constant “username”.

We pass first by an optional in order to avoid some errors. Indeed, if the user doesn’t input any data and the username variable is empty, without any optionals, we will get an error. But an optional can have an empty value.

So this allows us to create a conditional that will pass the value to username and show it, only if it is not empty.


Save an Array permanently

Now, that we know how to save a String permanently, let’s learn how to do it with an array.

Let’s consider the following array:

let array01 = [0,2,4,6]

Once, more to save the data, we will need to use the “UserDefaults” code.

UserDefaults.standard().set(array01, forKey: “array02”)

So to use it, we will do as above, with a small change:

let array01Object = UserDefaults.standard().object(forKey: “array02”)

if let array02 = array01Object as? Array {

print (array02) // this will output 0, 2, 4, 6



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Create a free website or blog at WordPress.com.

Up ↑

%d bloggers like this: