swiftswift2guardguard-statement

Swift 2.0 guard giving me errors


I was using the guard function and when I'd typed the guard statement below:

var IOUArray = [IOU(amount: 20, payer: "Isabella", description: 
"test"),IOU(amount: 30, payer: "Dad", description: "Test2")]
NSKeyedArchiver.archiveRootObject(IOUArray, toFile: "IOUArray")
guard
    let books = NSKeyedUnarchiver.unarchiveObjectWithFile("IOUArray") as? [IOU]

I got the error 'Expected else after guard condition' which wasn't a big deal because I wanted to put an else clause in anyway so I wrote:

else {return}

This time it threw up the error 'Return invalid outside of func' which was confusing and I have not seen this error before. So I then added nil to the state meant after return. Same Error. I don't know what is going on. Help will give you my infinite gratitude.


Solution

  • Else error. The guard condition must have an else-keyword. We can think of a guard as an if-else with an empty "if" and a requirement that the control flow terminates in the "else."

    Here is the correct code

    var IOUArray = [IOU(amount: 20, payer: "Isabella", description:
        "test"),IOU(amount: 30, payer: "Dad", description: "Test2")]
    NSKeyedArchiver.archiveRootObject(IOUArray, toFile: "IOUArray")
    guard let books = NSKeyedUnarchiver.unarchiveObjectWithFile("IOUArray") as? [IOU] else {
       return
    }