How to add nil into Array?
11,939
Solution 1
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.
Solution 2
You are trying to add a nil value to an array that doesn't accept nil values.
Try this:
For the array initialization:
var answersBody = [String?]()
And for when appending a value, remove the exclamation mark
self.answersBody.append(answer_body)
Author by
Toshi
Updated on June 07, 2022Comments
-
Toshi almost 2 years
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() }