2

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.

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
needshelp
  • 595
  • 1
  • 6
  • 25

2 Answers2

2

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
}
Rashwan L
  • 38,237
  • 7
  • 103
  • 107
1

error: return invalid outside of a func is reported by the compiler in the case you use returnstatement in global space. the else part of guard should never fall through, so if you remove return from it, another error occurs. check your code inside some function, to see the difference

user3441734
  • 16,722
  • 2
  • 40
  • 59