Reputation:
I am new in swift .. anyone help me to understand why this error throwing
Constant 'parsedResult' used before being initialized
on the other hand if i set return
in the catch
then compile error gone .what is the relation each other. explain please .
Here is my code :
if let data = data {
let parsedResult : AnyObject!
do {
parsedResult = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments)
}
catch{
print("something worng ")
// return
}
// error compiler error this line
print(parsedResult)
}
Upvotes: 0
Views: 1637
Reputation: 52530
This is easily fixed by declaring parseResult as AnyObject? which means it will be initialised to nil. The print will print an optional value which it can do just fine.
Be careful with the words you use. "// error throwing this line " is totally misleading. There is no error thrown at this line. Errors are thrown at runtime. You have the compiler reporting an error at this line. Be precise.
Upvotes: 1
Reputation: 8251
The way you have your code currently, parsedResult
might be uninitialized when you reach the print(parsedResult)
statement.
This can be the case when the try
statement throws an error. parsedResult
would still be uninitialized, the program would continue with the catch
block, print "something wrong" and then just continue (trying to print parsedResult
).
If you, however, insert a return
in your catch
block it ensures that in the case of an error, you wouldn't continue to the print(parsedResult)
line.
Upvotes: 0