Swift: Convert Unmanaged to String

Edit 1 (20th October 2014): Apple has now fixed this issue. To convert an unmanaged object to managed, just use the takeUnretainedValue() or the takeRetainedValue() method on it, based on whether you want to take a retained or unretained value.

So let’s say you have an Unmanaged<AnyObject> value that you know internally contains a value of type CFStringRef and you want to convert this to a value of type String in Swift. This is how I have managed to do that:

func convertCfTypeToString(cfValue: Unmanaged!) -> String?{

/* Coded by Vandad Nahavandipoor */

let value = Unmanaged.fromOpaque(
cfValue.toOpaque()).takeUnretainedValue() as CFStringRef
if CFGetTypeID(value) == CFStringGetTypeID(){
return value as String
} else {
return nil
}
}

Shown in Xcode it looks like this:

Screen Shot 2014-07-07 at 14.43.52

Leave a comment