Pardon me, sir, your Ref is showing. Here are five important things you might not know about using Core Foundation in Swift.
1. You don’t need to use “Ref” at the end of the name.
Swift remaps type names to ignore the dangling “Ref”. In Swift, all classes are actually reference types and the suffix isn’t needed.
Apple writes: “When Swift imports Core Foundation types, the compiler remaps the names of these types. The compiler removes Ref from the end of each type name because all Swift classes are reference types, therefore the suffix is redundant.”
2. CFTypeRef is AnyObject.
Just substitute AnyObject in anywhere you’d use CFType or CFTypeRef.
Apple writes:, “The Core Foundation CFTypeRef type completely remaps to the AnyObject type. Wherever you would use CFTypeRef, you should now use AnyObject in your code.”
3. Core Foundation is automatically memory managed.
Yes, there are a few remaining scraps here and there that aren’t properly migrated (you’ll know them because they return Unmanaged instances) but for the most part you don’t have to CFRetain, CFRelease, or CFAutorelease anything.
Apple writes, “Core Foundation objects returned from annotated APIs are automatically memory managed in Swift—you do not need to invoke the CFRetain, CFRelease, or CFAutorelease functions yourself.”
4. Toll Free Bridging is largely invisible although not perfect.
Wait a few weeks. It will probably get better.
Apple writes, “In Swift, you can use each pair of toll-free bridged Foundation and Core Foundation types interchangeably. You can also bridge some toll-free bridged Core Foundation types to Swift standard library types if you cast to a bridging Foundation type first.”
5. Annotate your objects
When you build custom CF objects from your own C or Objective-C methods, annotate them with CF_RETURNS_RETAINED or CF_RETURNS_NOT_RETAINED. Swift uses these hints to automatically memory manage your results. Thanks Cocoa Kevin, who taught me this: “The CoreFoundation naming rules is not enough according to the Swift compiler. If you don’t decorate your methods or functions then CoreFoundation objects will be returned as unmanaged.”
Apple writes, “If you return Core Foundation objects from your own C functions and Objective-C methods, annotate them with either CF_RETURNS_RETAINED or CF_RETURNS_NOT_RETAINED. The compiler automatically inserts memory management calls when it compiles Swift code that invokes these APIs.”