We have a case where we're being handed an object of type Array<Any>
which we need to convert to an Array<Codable>
. If any of the items in the original array don't adhere to Codable
, then we want the entire thing to abort and return nil.
Or current approach is to manually loop over everything, testing along the way, like so...
func makeCodable(sourceArray:Array<Any>) -> Array<Codable>?{
var codableArray = Array<Codable>()
for item in sourceArray{
guard let codableItem = item as? Codable else {
return nil
}
codableArray.append(codableItem)
}
return codableArray
}
However, I'm wondering if there's an easier way to do this with the map
command, but it would require it to short-circuit if any of the elements can't be mapped. That's what I'm not sure or not is possible.
For instance, this pseudo-code...
func makeCodable(sourceArray:Array<Any>) -> Array<Codable>?{
return sourceArray.map({ $0 as? Codable});
}
Is this possible, or is our original way the correct/only way?