John
John

Reputation: 77

Dealing with cluttering swift optionals

I am writing some Swift code that should really be simple: initialization of a database class which loads data from a file if available or returns an empty database otherwise.

The issue is, my code seems overly complicated and I think there might be a better way of dealing with optional values that I fail to see.

Here is how I do it vs. how I would like it to be :

How I do

class Database: NSObject
{
    private var database:    [String: [AnyObject]]
    private var databasePath: String

    init(databasePath: String)
    {
        self.databasePath = databasePath

        if let db1 = NSKeyedUnarchiver.unarchiveObjectWithFile(databasePath)
        {
            if let db2 = db1 as? [String : [AnyObject]]
            {
                database = db2
            }
            else
            {
                database = [String: [AnyObject]]()
            }
        }
        else
        {
            database = [String: [AnyObject]]()
        }

        super.init()
    }
}

How I would like it to be

class Database: NSObject
{
    private var database:    [String: [AnyObject]]
    private var databasePath: String

    init(databasePath: String)
    {
        self.databasePath = databasePath

        if !(let database = NSKeyedUnarchiver.unarchiveObjectWithFile(databasePath) as? [String : [AnyObject]])
        {
            database = [String: [AnyObject]]()
        }

        super.init()
    }
}

What did I miss ?

Upvotes: 1

Views: 43

Answers (1)

Martin R
Martin R

Reputation: 539685

You can simplify it to

if let db = NSKeyedUnarchiver.unarchiveObjectWithFile(databasePath) as? [String : [AnyObject]] {
    database =  db
} else {
    database = [:]
}

or even to a single statement, using the "nil-coalescing operator" ??:

database = NSKeyedUnarchiver.unarchiveObjectWithFile(databasePath) as? [String : [AnyObject]] ?? [:]

This evaluates to the first expression

NSKeyedUnarchiver.unarchiveObjectWithFile(databasePath) as? [String : [AnyObject]]

if that is not nil, and to the empty dictionary [:] otherwise.

Upvotes: 4

Related Questions