Parse json object in swift 2

I am new to iOS and Swift programming, I am trying to create a method to parse a json object

My json looks like this

{
 status : true;
 data :[
   "url" : "",
   "startDate" : "",
   "endDate" : "",
...
]
}

my swift code is like

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 get below the error

Return from initializer without initializing all stored properties
+4
source share
2 answers

Your problem is that the compiler does not know how to initialize your values ​​if the condition if let item = ...does not work.

You have two parameters that are described for the condition status, but inside the branch trueyou create a new condition that does not have an else branch, so the compiler correctly complains about uninitialized stored properties.

- data[DATA] , .

+1

,

, , .

, , , , , . nil, .

, ,

status      = data[STATUS] as! Bool;

, .

, status == true , , , . , .

0

Source: https://habr.com/ru/post/1626579/


All Articles