Search code examples
iosobjective-cswiftnsarray

Read NSArray of CGPoints in Swift


I have a function in an Objective-C class that returns an NSArray:

- (NSArray *) myAwesomeFunction {
   // Good stuff here
   return array
}

Now I know that the members of this array are all NSValue objects with a CGPoint inside. This information is not available to Swift however, which infers the return type (correctly) as [AnyObject]!

Now when I try to cast the members of the array into an NSValue I get a cast error as I should.

let myArray = AnObjectiveCClass.myAwesomeFunction()
let myValue = myArray[0] as NSValue // Cast error since AnyObject cannot be cast to NSValue

This leaves me with a problem though, how can I access the contents of the array in my Swift class? In the end I want to retrieve the CGPoint values inside of the array.


Solution

  • In my opinion, you can cast the the whole array to a [NSValue] array:

    if let downcastNSValueArray = myArray as? [NSValue] {
        let myValue = downcastNSValueArray[0]
    }