在Swift 2中解析json对象 [英] parse json object in swift 2

查看:121
本文介绍了在Swift 2中解析json对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是iOS和Swift编程的新手,我正在尝试建立一种解析json对象的方法

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

我的json如下

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

我的代码很快就是

导入基金会

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 = "";
        }
    }
}

我遇到错误了

Return from initializer without initializing all stored properties

推荐答案

您的问题是,如果if let item = ...条件失败,编译器将不知道如何初始化您的值.

Your issue is that the compiler doesn't known how to initialize your values if the if let item = ... condition fails.

对于status条件,您有两个选择,但是在true分支中,您创建了一个没有else分支的新条件,因此编译器会正确地抱怨未初始化的存储属性.

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.

我的建议是先 安全地展开data[DATA],而不创建新的作用域,然后使用这些值.

My suggestion is to first safely unwrap data[DATA] without making a new scope, then use the values.

这篇关于在Swift 2中解析json对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆