dzheng dzheng - 29 days ago 8
Swift Question

concatenate in swift3.0: Binary operator '+' cannot be applied to operands of type '[]' and '[]?'

get the error in Swift3.0:


Binary operator '+' cannot be applied to operands of type '[FutureTrainee]' and '[FutureTrainee]?'


Code:

let newTrainees = data?["data"].arrayValue.map({ (json) in
return FutureTrainee(data: json)
})
let trainees = self.futureTraineeCollection.futureTrainees + newTrainees

Answer

Just as the error suggests, you can't use + to add [FutureTrainee] (a.k.a Array<FutureTrainee>) and [FutureTrainee]? (a.k.a. Optional<Array<FutureTrainee>>.

newTrainees has type [FutureTrainee]? because you used optional chaining to subscript data with "data". This code:

let newTrainees = data?["data"].arrayValue.map({ (json) in
                        return FutureTrainee(data: json)
                    }) 

is like:

var newTrainees: [FutureTrainee]?
if let data = data {
    newTrainees = data["data"].arrayValue.map({ (json) in
                      return FutureTrainee(data: json)
                  })
else {
    newTrainees = nil
}

You need to make sure you only append the newTrainees if it's not nil, like so:

var trainees = self.futureTraineeCollection

if let newTrainees = data?["data"].arrayValue.map{ FutureTrainee(data: $0) } {
    // If that expression is not nil, the result is bound to "newTrainees"
    trainees += newTrainees
}