Reputation: 9394
I am new in iOS and Swift programming, I am trying to make a method to parse json object
My json is as following
{
status : true;
data :[
"url" : "",
"startDate" : "",
"endDate" : "",
...
]
}
my code in swift is like that
import Foundation
class SplashResponse {
let STATUS = "status";
let DATA = "data";
let URL = "Url"
let CONTACT_NO = "ContactNo";
let SPLASH_IMAGE = "SplashImage";
let SPLASH_ID = "SplashId";
let TITLE = "Title";
let NO_VIEW = "NoView";
let IS_ACTIVE = "isActive";
let START_DATE = "StartDate";
let END_DATE = "EndDate";
var status : Bool
var url : String
var contactNo : String
var splashImage : String
var splashId : Int
var title : String
var numOfViews : Int
var isActive : Bool
var startDate : String
var endDate : String
init(data : NSDictionary){
status = data[STATUS] as! Bool;
if (status == true) {
if let item = data[DATA] as? [String: AnyObject] {
url = item[URL] as! String;
contactNo = item[CONTACT_NO] as! String;
splashImage = item[SPLASH_IMAGE] as! String;
splashId = item[SPLASH_ID] as! Int;
title = item[TITLE] as! String;
numOfViews = item[NO_VIEW] as! Int;
isActive = item[IS_ACTIVE] as! Bool;
startDate = item[START_DATE] as! String;
endDate = item[END_DATE] as! String;
}
} else {
url = "";
contactNo = "";
splashImage = "";
splashId = -1;
title = "";
numOfViews = -1;
isActive = false;
startDate = "";
endDate = "";
}
}
}
I am getting below error
Return from initializer without initializing all stored properties
Upvotes: 4
Views: 149
Reputation: 8441
The error message is clear enough,
Return from initializer without initializing all stored properties
and clearly all of your properties are stored properties.
So you have to make sure once you initializer returned, every single stored properties will have it's value. It can be either nil or some value.
In your case, first of all,
status = data[STATUS] as! Bool;
may fail, thus all the rest will not be executed.
Even though, status == true
may succeed, all the code that come with this condition may fail. And that's violating the rule that I just mentioned.
Upvotes: 0
Reputation: 70097
Your issue is that the compiler doesn't known how to initialize your values if the if let item = ...
condition fails.
You have your two options covered for the status
condition, but inside the true
branch you create a new condition which has no else branch, so the compiler complains rightly about non-initialized stored properties.
My suggestion is to first safely unwrap data[DATA]
without making a new scope, then use the values.
Upvotes: 1