Evgeniy Kleban
Evgeniy Kleban

Reputation: 6940

Cast Array<Any> to Array<Int> in Swift

I have array of Any objects called timestamps, in which first object is string, and rest objects are Int. What i want is, to drop first element and treat rest of array as Array of Int objects..

I tried:

let timestamps = xAxisData.dropFirst()
if let timestamps = timestamps as? Array<Int> { 
}

It compile, but it says - Cast from 'ArraySlice<Any>' to unrelated type 'Array<Int>' always fails

I could possibly iterate through array and create new temporary array with check every element whether it Int or not, but i think there is a better cleaner way?

Upvotes: 0

Views: 2296

Answers (3)

Aaron Cyrman
Aaron Cyrman

Reputation: 556

I like to use something like a flatMap so no matter were the non-Int values are in the array they are not consider for the resulting array.

let originalArray:[Any] = ["No int", 2, 3, "Also not int", 666, 423]
let intArray:[Int] = originalArray.flatMap { $0 as? Int }
print(intArray)

Will print this:

[2, 3, 666, 423]

So in your case you could do something like:

let timestamps = xAxisData.flatMap { $0 as? Int }

As stated by Steve Madsen in the comment below, if you are using Swift 4.1 or newer Apple suggest to used compactMap for getting rid of optional nils so that specific use of flatMap is deprecated.

let timestamps = xAxisData.compactMap { $0 as? Int }

Upvotes: 2

Steve Madsen
Steve Madsen

Reputation: 13791

Here is another method to convert a subset of an array with mixed types to something more specific:

let intArray = anyArray.compactMap { $0 as? Int }

Upvotes: 1

rmaddy
rmaddy

Reputation: 318774

You need to create an Array from the ArraySlice created by dropFirst.

let timestamps = Array(xAxisData.dropFirst())
if let timestamps = timestamps as? [Int] { 
}

Upvotes: 3

Related Questions