3
votes

How do I use the switch statement on UIImagePickerControllerMediaType?

The following example throws the strange compiler error:

Expression pattern of type 'CFString' cannot match values of type 'CFString'.

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {

    switch info[UIImagePickerControllerMediaType] as! CFString {

    case kUTTypeImage:
        break

    default:
        break
    }
}
2

2 Answers

5
votes

I can suggest two ways to solve this inconvenience.

Cast to String

Simple, but requires extra typing.

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {

    switch info[UIImagePickerControllerMediaType] as! String {
        case String(kUTTypeImage):
            break
        default:
            break
    }
}

Implement pattern matching operator for CFString type

More tricky, but less typing if you need switching on CFString often.

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {

    switch info[UIImagePickerControllerMediaType] as! CFString {
        case kUTTypeImage:
            break
        default:
            break
    }
}

func ~=(pattern: CFString, value: CFString) -> Bool {
    return pattern == value
}

See section "Expression Pattern" in Patterns chapter in the language reference (Swift 2.2).

1
votes

Another way to solve this is casting to NSString:

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {

    switch info[UIImagePickerControllerMediaType] as! NSString {
        case kUTTypeImage:
            break
        default:
            break
    }
}