swiftcfstring

Question about CFArrayGetValueAtIndex in Swift


I called this to get an array of attribute names of an AXUIElement element.

    var attrNames: CFArray? = nil;
    AXUIElementCopyAttributeNames(element, &attrNames);

My understanding is that attrNames is a CFArray of CFString.

I then call:

var foo = CFArrayGetValueAtIndex(attrNames!, idx)

In Objective-C, this corresponding call returns an NSArray* of CFString*. How do I access the individual strings of this array in Swift?

I tried this: let attrName : NSString = (NSString) CFArrayGetValueAtIndex(attrNames!, index);

but it won't compile: Cannot convert value of type '(NSString).Type' to specified type 'NSString'

I also tried CFString instead of NSString, but got a similar message.


Solution

  • Don't use CFArray at all; it isn't Swift. Cast the CFArray safely to a Swift array of String, and then talk Swift, using subscripting to index the array as usual. Thus for example:

    var attrNames: CFArray?
    AXUIElementCopyAttributeNames(element, &attrNames)
    guard let attrNames = attrNames as? [String] else { return }
    var foo = attrNames[idx]