0

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?

3
  • You're wrapping Books.books(fromDictArray: arrayOfBooks) in an array literal. You probably didn't mean to do that ;) Commented Apr 22, 2017 at 23:05
  • @Hamish, what do you mean by that? Commented Apr 22, 2017 at 23:09
  • Square brackets are used to make an array literal – so when you say [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. Commented Apr 22, 2017 at 23:12

1 Answer 1

2

You shouldn't have it in the []. Instead try:

let inventoryBooks = Books.books(fromDictArray: arrayOfBooks).flatMap{$0}

Having it is the [] is making an array with one item in it, the result of the fromDictArray call. So it's structured like [[1, 2, 3]] instead of [1, 2, 3]. So when you call flatmap it checks that one item, which that isn't nil, and returns it.

Sign up to request clarification or add additional context in comments.

3 Comments

You forgot to apply your own suggestion to the code ;) And it's the flattening version of flatMap(_:) that is called with the [[Books?]], not the optional unwrapping one – so you get back a [Books?].
What do you mean? It looks right to me now. ;) Went too quick with the copy and paste. Thanks.
I mean saying "So when you call flatmap it checks that one item, which that isn't nil, and returns it." isn't correct, as it's the flattening version of flatMap(_:) being called, so there's no nil check going on – it's simply getting rid of one nesting layer, returning a [Books?]. If it were the optional unwrapping version of flatMap(_:) being called, you'd get back a [[Books?]].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.