Casting arrays

**Casting Array to Array**

let arrayOfAny:[Any] = [1,"2",3.0,CGFloat(4)]
let stringArray:[String] = {String($0)}
print(stringArray)//"1", "2", "3.0","4.0"

Sometimes its useful to convert from one array type to another. But be aware that the .map method iterates over the entire array and returns a “new copy” <–(situation needed for this statement). The best approach is in most cases not to convert the array type but to either do instance checking before packing the array or instance checking after unpacking the array

You can also do this (only applicable with AnyObject arrays):

let someArray:[AnyObject] = ["1","a","xyz"]
let stringArray:[String] = someArray as! [String]

it also seems you can down cast an array if the array extends the class at some point (This only works in one direction aka: upcasting not down casting)

if you use flatMap instead of map you remove all nil values in that array

let a:[String?] = ["a",nil,"b",nil]
let b:[String] = a.flatMap{$0}//you can also do map{$0!}<--flat map flattens nested arrays, in that case use map
Swift.print(b)//["a", "b"]

NOTE: It seems using .map is the only way to downcast an array. And it seems to not create copies but real references

let list:[NSXMLElement] = xml.children as! [NSXMLElement]//xml.children returns an array with NSXMLNode items But NSXMLNode extends NSXMLElement, so it will work

Map example:

class A:B{
    var value:String = "default"
    init(_ value:String){
        self.value = value
class B{
    var someNum:CGFloat = 1
var arr1:[A] = [A("a"),A("b"),A("c")]

let arr2:[B] = { $0 as B }//arr1 as! [A]//

//Further testing should be done to verify if the original refrences are intact