3
\$\begingroup\$

I'm very new to Swift and programming in general. I'm creating a quiz application and am trying to create a function that will save the number of times a user has completed a quiz.

It appears to work through testing but I was wondering if there was a more elegant way to write this function:

func plusTestsTaken() {
    var testsTakenSave = NSUserDefaults.standardUserDefaults()

    if testsTakenSave.integerForKey("testsTaken") >= 1 {
        var testsTakenCount = testsTakenSave.valueForKey("testsTaken") as! Int
        testsTakenCount++
        testsTakenSave.setValue(testsTakenCount, forKey: "testsTaken")
        testsTakenSave.synchronize()
        println("Test again \(testsTakenCount)")
    } else {
        var testsTakenCount = 1
        testsTakenSave.setValue(testsTakenCount, forKey: "testsTaken")
        testsTakenSave.synchronize()
        println("Test number \(testsTakenCount)")
    }
}
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

Calling synchronize is completely unnecessary and is actually a performance bottleneck. For more information about synchronize, take a look at this Stack Overflow answer. So we can go ahead and remove that line.

We can also get rid of the println as that's not really doing us much good. There's not much point to it at all, especially if this is an iOS application.

We can make our logic a little better here too. Let's avoid grabbing our value out of NSUserDefaults multiple times using an if let. We can also take advantage of the fact that if the value has never been set for our key, grabbing it with integerForKey will return 0. So, we can handle all scenarios the same:

let kKEY_TestsTaken = "testsTaken"
let defaults = NSUserDefaults.standardUserDefaults()
let testsTaken = defaults.integerForKey(kKEY_TestsTaken)
defaults.setInteger(testsTaken + 1, forKey: kKEY_TestsTaken)

The only remaining comment I have is that we can make our method name more clear. Also, there's no reason not to give the user the ability to increment the test count by more than one.

func incrementTestCount(value: Int = 1) {
    let kKEY_TestsTaken = "testsTaken"
    let defaults = NSUserDefaults.standardUserDefaults()
    let testsTaken = defaults.integerForKey(kKEY_TestsTaken)
    defaults.setInteger(testsTaken + value, forKey: kKEY_TestsTaken)
}
\$\endgroup\$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.