array to not array in swift

To convert an array to a non-array type in Swift, you need to perform a process called "type casting". Here's an example of how to do this:

main.swift
let myArray = [1, 2, 3, 4, 5]
let myNonArray = myArray as AnyObject
68 chars
3 lines

In this example, myArray is an array of integers. We use the as AnyObject keyword to convert myArray to a non-array type. This is possible because in Swift, arrays are considered a type of object. Once we've converted our array to a non-array type, we can use it as such:

main.swift
print(myNonArray) // prints "Optional([1, 2, 3, 4, 5])"
56 chars
2 lines

Note that when we type cast an array to a non-array type, it becomes an optional value. This is because there's no guarantee that the type cast will succeed. So, we should use optional binding to safely unwrap the value:

main.swift
if let myNonArray = myArray as AnyObject? {
    print(myNonArray) // prints "[1, 2, 3, 4, 5]"
} else {
    print("Could not convert array to non-array type.")
}
161 chars
6 lines

In this code block, we use optional binding to safely unwrap myNonArray. If the type cast succeeds, we print out its value. Otherwise, we print an error message.

gistlibby LogSnag