Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

swift

xcode6

ios8

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'

like image 550
leonard Avatar asked Jan 10 '23 09:01

leonard


2 Answers

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.

like image 160
rickster Avatar answered Jan 16 '23 21:01

rickster


var str = "string"
var cfstr:CFString = str as NSString // OR str.__conversion()
like image 38
Joseph Mark Avatar answered Jan 16 '23 22:01

Joseph Mark