How to test UIImagePickerControllerMediaType for kUTTypeImage?

482 Views Asked by At

In the delegate method of UIImagePickerViewController, I want to test for the media type.

This worked in Swift 3:

switch info[UIImagePickerControllerMediaType] as? NSString {

    case .some(kUTTypeImage):
    //...
}

But in Swift 4, it throws an error:

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

I changed it to this without error, but the type conversion doesn't look elegant:

switch info[UIImagePickerControllerMediaType] as? String {

    case .some(kUTTypeImage as NSString as String):
    //...
}

I tried to shorten it:

switch info[UIImagePickerControllerMediaType] as? NSString {

    case .some(kUTTypeImage as NSString):
    // ...
}

But this throws the error again:

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

a) Why does the shorter version throw an error but the longer version doesn't?

b) Is there a more elegant (shorter) way to write this?

1

There are 1 best solutions below

3
Tamás Sengel On

You should cast the dictionary element to CFString.

let mediaType = info[UIImagePickerControllerMediaType] as! CFString

switch mediaType {
case kUTTypeImage:
    //
default: break
}

Strangely enough, if I try to conditionally unwrap mediaType, Xcode will complain:

Conditional downcast to CoreFoundation type 'CFString' will always succeed

...and if I try to use simply as CFString, as it "will always succeed":

'Any?' is not convertible to 'CFString'; did you mean to use 'as!' to force downcast?

Strange, seems like the compiler is a little confused. Anyway, it's one of the few instances where force unwrapping is the most elegant solution.