leonard
leonard

Reputation: 2387

How to convert a String type variable to CFString in Swift?

I learned this from iOS tutorial, but it doesn't work

func imagePickerController(picker: UIImagePickerController!, didFinishPickingMediaWithInfo info: NSDictionary!) {
    var mediaType = info.objectForKey(UIImagePickerControllerMediaType) as String
    var originalImage, editedImage, imageToUse: UIImage

    // Handle a still image picked from a photo album
    if (CFStringCompare(CFStringRef(mediaType), kUTTypeImage, 0) == CFComparisonResult.CompareEqualTo) {
        editedImage = info.objectForKey(UIImagePickerControllerEditedImage) as UIImage
        originalImage = info.objectForKey(UIImagePickerControllerOriginalImage) as UIImage

        if (editedImage) {
            imageToUse = editedImage
        } else {
            imageToUse = originalImage
        }

        // Do something with imageToUse
    }

It constantly alerts me

CFStringRef is not constructible with '@lvalue String'

So I tried this:

// Handle a still image picked from a photo album
    var temp = mediaType as CFString
    if (CFStringCompare(temp, kUTTypeImage, 0) == CFComparisonResult.CompareEqualTo) {
        editedImage = info.objectForKey(UIImagePickerControllerEditedImage) as UIImage
        originalImage = info.objectForKey(UIImagePickerControllerOriginalImage) as UIImage

And it alerts me with

Cannot convert the expression's type 'CFString' to type '$T1'

Upvotes: 5

Views: 6943

Answers (2)

Joseph Mark
Joseph Mark

Reputation: 9418

var str = "string"
var cfstr:CFString = str as NSString // OR str.__conversion()

Upvotes: 2

rickster
rickster

Reputation: 126107

Swift.String and NSString bridge automatically, and NSString and CFString can be cast to one another, but you can't (for now?) transitively get all the way from a Swift String to a CFString without an extra cast or two.

Here's a Swift string, a function that takes a CFString, and how to call it by casting to NSString:

var str = "Hello, playground"

func takesCFString(s: CFString) {}

takesCFString(str as NSString)

Note you don't need to use CFStringRefin Swift (and most of the Swift declarations of CFString API don't). The compiler takes advantage of the automatic ARC bridging for CF types that was introduced with Xcode 5 to let you treat those types like Swift (or ObjC) objects.

Upvotes: 7

Related Questions