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)

Reading: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/OptionalChaining.html

Share:
11,939
Toshi
Author by

Toshi

Updated on June 07, 2022

Comments

  • Toshi
    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()
        }