micyukcha
micyukcha

Reputation: 367

Swift: flatmap still returning optional

I'm trying to match the objects in my AnyObject array to a particular string and I've gone down the path of flatmap to return a non-optional array but still getting optional back.

typealias PropertyList = [AnyObject]

var savedProgram: PropertyList?
var savedProgramUnwrapped = savedProgram.flatMap{ $0 }

savedProgram
savedProgramUnwrapped
print(savedProgramUnwrapped)
print(savedProgram)

Why do savedProgram and savedProgramUnwrapped still look the same?

Upvotes: 0

Views: 434

Answers (2)

Tim Vermeulen
Tim Vermeulen

Reputation: 12562

flatMap can remove optional values from an array. You have an optional array, not an array of optionals. This works fine:

let arrayOfOptionals: [Int?] = [1, nil, 5, 2, nil]
let arrayOfNumbers = arrayOfOptionals.flatMap { $0 }
print(arrayOfNumbers) // [1, 5, 2]

Upvotes: 2

Yury
Yury

Reputation: 6114

Because flatMap method do nothing in your case. This method have effect on Element of array, but your elements anyway non-optional

Upvotes: 0

Related Questions