Jim Jim - 3 years ago 177
Swift Question

Why does fixing 'initialization of variable 'error' was never used;' result in a new error

I'm learning from a tutorial that I had to convert to the newest version of Swift. It went mostly well except that I'm stuck with a warning: "Initialization of variable 'error' was never used; consider replacing its assignment to '_' or removing. Here's the code:

class func loadMembersFromFile(path:String) -> [Member]
var members:[Member] = []

var error:NSError? = nil
if let data = try? NSData(contentsOfFile: path, options:[]) ,
json = (try? NSJSONSerialization.JSONObjectWithData(data, options: [])) as? NSDictionary,
team = json["team"] as? [NSDictionary] {
for memberDictionary in team {
let member = Member(dictionary: memberDictionary)
return members

I understand that error so I'm following Xcode's advice and changing the offending line to:

_:NSError? = nil

That results in two new errors; 'Consecutive statements on a line must be separated by ';' and 'Expected expression'

It's pretty obvious these are syntax errors so I hope this isn't a dumb question but which are the consecutive statements? Also, why would these errors only appear after I make a change Xcode is suggesting?

Answer Source

I tried it out myself, it seems that Xcode's "advice" also deleted the let keyword instead of leaving it with the new variable name, _.

Since there is no longer any variable assignment, a syntax error comes up. The two consecutive statements Xcode is seeing are _ and :NSError = nil. So, it thinks you've made a mistake and forgotten to put a semicolon between two statements on the same line (Consecutive statements on the same line must be replace by a ';'). It advises you to put a semicolon there, and when you do, it realises that neither _ nor :NSError = nil are valid expressions, and tells you so with Expected Expression.

But none of that matters, because Error Handling has moved from NSErrors to try/catch and that NSError isn't used anymore. You'll be fine just deleting it. PS, you should put any code with try statements in a do block and then handle any errors in a catch block

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download