How to add nil into Array?

lalala

I'd like to add nil into Array,set as answersBody.

var answersBody = [String]()

When answer_body is nil, it returns error.Could you tell me how to solve the problem?

  Alamofire.request(.GET, "http://localhost:3000/api/v1/questions/index",parameters: nil, encoding: .JSON)
        .responseJSON { (request, response, data, error) in
            var jsonObj = JSON(data!)
            var questions_count = jsonObj["questions"].count

            for var index = 0; index < questions_count; index++ {
                let answer_body = jsonObj["questions"][index]["answers"]["body"].string
                self.answersBody.append(answer_body!)
            }
            self.tableView.reloadData()
    }
neo

Make array type [String?] which is optional string. It can be set to nil. Regular String type can't be nil.

And then

if let body = answerBody{
    self.answersBody.append(body)
}
else{
    self.answersBody.append(nil)
}

let would unwrap your optional. If it's not nil, then it would enter into if; otherwise else would execute.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related