如何在UIImagePickerControllerMediaType上使用switch语句?

时间:2016-04-22 15:08:18

标签: swift switch-statement uiimagepickercontroller

如何在UIImagePickerControllerMediaType上使用switch语句?

以下示例抛出奇怪的编译器错误:

  

“CFString”类型的表达式模式不能匹配类型的值   'CFString字符串'

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

    switch info[UIImagePickerControllerMediaType] as! CFString {

    case kUTTypeImage:
        break

    default:
        break
    }
}

2 个答案:

答案 0 :(得分:4)

我可以提出两种解决这种不便的方法。

转换为字符串

简单,但需要额外输入。

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

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

为CFString类型

实现模式匹配运算符

更棘手,但如果您需要经常打开CFString,请减少输入。

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
}

参见" Expression Pattern"在语言参考的Patterns章节中(Swift 2.2)。

答案 1 :(得分:1)

解决此问题的另一种方法是转换为NSString

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

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