Consider this code snippet:
var a: String? = "abc"
var b: String?
let result = [a, b].compactMap { $0 }
After executing it, result
will be
["abc"]
which is the expected result. The element of result (ElementOfResult
) here is String
.
print(type(of: result))
Array<String>
Now to the interesting part. After changing the snippet to
var a: String? = "abc"
var b: Int?
let result = [a, b].compactMap { $0 }
and executing it, result
will be
[Optional("abc"), nil]
The element of result (ElementOfResult
) here is Any
which makes sense, because Any
is the common denominator of String
and Int
.
print(type(of: result))
Array<Any>
Why was a nil
result returned by compactMap
which contradicts its definition?
From Apple's compactMap
documentation
compactMap(_:)
Returns an array containing the non-nil results of calling the given transformation with each element of this sequence.
Declaration
func compactMap(_ transform: (Self.Element) throws -> ElementOfResult?) rethrows -> [ElementOfResult]