展开非零值时发现为零

时间:2015-02-25 10:39:40

标签: ios swift null unwrap

我正在尝试通过swift传递以下参数来获取请求

var dict = [
    "id_struttura" : 2,
    "prenCheck" : [
        "codice" : "14:30_15:20_1_3831_0",
        "id_sport" : 6,
        "ora_fine" : "20/02/2015 15:20:00",
        "ora_inizio" : "20/02/2015 14:30:00",
        "rec" : 0,
        "soci" : [
            [
                "esterno" : 0,
                "id" : "1980"
            ],
            [
                "esterno" : 0,
                "id" : "51"
            ]
        ]
    ]
]

使用以下方法:

private func genericRequest(method: Methods, url: String, data: [String: AnyObject]?) -> AnyObject?{
    var getRequest : NSURLRequest?
    var postRequest : NSMutableURLRequest?

    if method == Methods.GET{
        var completeUrl = url

        if(data != nil){
            //println(data)
            completeUrl += "?"
            for (key, value) in data! {

                completeUrl += "\(key)=\(value)&"
            }
            completeUrl = completeUrl.substringToIndex(completeUrl.endIndex.predecessor())
        }
        //println(completeUrl)

        let url = NSURL(string: completeUrl)
        getRequest = NSURLRequest(URL: url!)

    }else if method == Methods.POST{
        postRequest = NSMutableURLRequest(URL: NSURL(string: url)!)
        var session = NSURLSession.sharedSession()
        postRequest!.HTTPMethod = "POST"

        var params : String = ""

        for (key, value) in data! {

            params += "\(key)=\(value)&"
        }
        params = params.substringToIndex(params.endIndex.predecessor())

        var err: NSError?
        postRequest!.HTTPBody = params.dataUsingEncoding(NSUTF8StringEncoding);
    }

    var response: NSURLResponse? = nil
    var error: NSError? = nil
    var request = getRequest != nil ? getRequest! : postRequest!
    let reply = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&error)

    //println((response as NSHTTPURLResponse).statusCode)
    let results = NSString(data:reply!, encoding:NSUTF8StringEncoding)
    var json: AnyObject? = convertDataToJSON(reply)
    return json
}

将其称为genericRequest(Method.GET ,url:url, data: dict)(因为Method只是一个枚举),它在发出get请求时无法在for (key,value)in data!中解包数据变量,但它可以在发出post请求时。因为我必须只使用获取此任务的请求(我正在处理一个糟糕的休息界面),有人可以帮助我吗?

更新: 我还尝试使用if let data = data { ...并在此行崩溃说unexpectedly found nil while unwrapping an Optional value

2 个答案:

答案 0 :(得分:0)

你正在使用大量的力量展开(!)。你所做的每个地方都是一个你承诺编译器的地方,可选的永远不会是零。在大多数地方,我认为您应该允许编译器通过使用其他处理选项的方法来证明零安全性(可选链接,零合并,映射等)。

在您的具体情况下,我不知道您为什么不这样做:

if let data = data {

而不是:

if (data != nil) {

然后不得不用!强制解包数据。

我最近bloggedtalked有关在Swift中处理选项的工具,如果你想了解更多关于如何不强制解包的信息。

答案 1 :(得分:0)

为什么不像在GET方法中那样检查POST方法中的数据是否为nil。我认为post方法是你试图解开nil的地方

if method == Methods.GET{
    var completeUrl = url

    // here you check if data is nil
    if(data != nil){
        //println(data)
        completeUrl += "?"
        for (key, value) in data! {

            completeUrl += "\(key)=\(value)&"
        }
        completeUrl = completeUrl.substringToIndex(completeUrl.endIndex.predecessor())
    }
    //println(completeUrl)

    let url = NSURL(string: completeUrl)
    getRequest = NSURLRequest(URL: url!)

}else if method == Methods.POST{
    postRequest = NSMutableURLRequest(URL: NSURL(string: url)!)
    var session = NSURLSession.sharedSession()
    postRequest!.HTTPMethod = "POST"

    var params : String = ""
    //check here as well
    if data != nil{
        for (key, value) in data! {

            params += "\(key)=\(value)&"
        }
        params = params.substringToIndex(params.endIndex.predecessor())
    }

    var err: NSError?
    postRequest!.HTTPBody = params.dataUsingEncoding(NSUTF8StringEncoding);
}