0

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?

1
  • 3
    "in which first object is string, and rest objects are Int." This indicates you've used the wrong datatype. You meant to use a struct Timestamps { let something: String; values: [Int] } here, not an [Any]. Building things on Any is going to bite you again and again. Commented Mar 13, 2019 at 17:41

3 Answers 3

3

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

let timestamps = Array(xAxisData.dropFirst())
if let timestamps = timestamps as? [Int] { 
}
Sign up to request clarification or add additional context in comments.

Comments

2

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 }

2 Comments

Swift 4.1 deprecated the use of flatMap in favor of compactMap to remove optionals from a sequence.
Thanks Steve, I edited the answer to add your input.
1

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 }

3 Comments

not really efficient because i know that first element will be string, your solution is O(n) complexity.
True; for your specific use case @rmaddy's solution is more appropriate. In terms of your question's title, though, a more general solution should be useful to others.
An as? cast on an array is O(n) anyway since it has to check every element

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.