Skip to content

Commit 82597fd

Browse files
committed
Add a slightly cheaper, but still O(n), conversion for CFArrayRef -> Array<T>
1 parent 281aa0f commit 82597fd

File tree

1 file changed

+14
-0
lines changed

1 file changed

+14
-0
lines changed

Foundation/NSArray.swift

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -502,6 +502,20 @@ extension CFArrayRef : _NSBridgable, _SwiftBridgable {
502502
internal var _swiftObject: Array<AnyObject> { return _nsObject._swiftObject }
503503
}
504504

505+
extension CFArrayRef {
506+
/// Bridge something returned from CF to an Array<T>. Useful when we already know that a CFArray contains objects that are toll-free bridged with Swift objects, e.g. CFArray<CFURLRef>.
507+
/// - Note: This bridging operation is unfortunately still O(n), but it only traverses the NSArray once, creating the Swift array and casting at the same time.
508+
func _unsafeTypedBridge<T : AnyObject>() -> Array<T> {
509+
var result = Array<T>()
510+
let count = CFArrayGetCount(self)
511+
result.reserveCapacity(count)
512+
for i in 0..<count {
513+
result.append(unsafeBitCast(CFArrayGetValueAtIndex(self, i), T.self))
514+
}
515+
return result
516+
}
517+
}
518+
505519
extension Array : _NSBridgable, _CFBridgable {
506520
internal var _nsObject: NSArray { return _bridgeToObject() }
507521
internal var _cfObject: CFArrayRef { return _nsObject._cfObject }

0 commit comments

Comments
 (0)