Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add nil into Array?

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()
    }
like image 767
Toshi Avatar asked Jul 21 '15 11:07

Toshi


People also ask

How do you nil an array in Swift?

There is a method for that: class Array { lazy var elementsInArray = [Int]() func add(element: Int) { elementsInArray. append(element) } func clear() { elementsInArray. removeAll() //use this. } }

How to remove nil from ruby Array?

Syntax: Array. compact() Parameter: Array to remove the 'nil' value from. Return: removes all the nil values from the array.

Can you add arrays in Swift?

To append another Array to this Array in Swift, call append(contentsOf:) method on this array, and pass the other array for contentsOf parameter. append(contentsOf:) method appends the given array to the end of this array.


2 Answers

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.

like image 119
neo Avatar answered Oct 29 '22 07:10

neo


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

like image 36
Laffen Avatar answered Oct 29 '22 07:10

Laffen