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()
}
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. } }
Syntax: Array. compact() Parameter: Array to remove the 'nil' value from. Return: removes all the nil values from the array.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With