I'm trying to remove the nil objects from array I'm getting when I'm generating objects:
static func books(fromDictArray array: [[String: Any]]) -> [Books?] {
return array.map(GettyTwo.init)
}
Here I'm trying to only take the non nil objects:
let inventoryBooks = [Books.books(fromDictArray: arrayOfBooks)].flatMap{$0} //this doesn't remove the nil objects
But if I do it this way:
let noNilElements = inventoryBooks.flatMap{$0}
This will remove the nil objects.
My question to you guys is why this is not working:
let inventoryBooks = [Books.books(fromDictArray: arrayOfBooks)].flatMap{$0}
What I'm doing wrong?
Books.books(fromDictArray: arrayOfBooks)in an array literal. You probably didn't mean to do that ;)[Books.books(fromDictArray: arrayOfBooks)], you get a[[Books?]], not a[Books?].flatMap(_:)can flatten nested arrays, so that's what it does – giving you back a[Books?]. Just get rid of the square brackets.