Manuel Manuel - 7 months ago 16
Swift Question

How to use the switch statement on UIImagePickerControllerMediaType?

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
}
}

Answer

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).

Comments