如何在UIImagePickerControllerMediaType
上使用switch语句?
以下示例抛出奇怪的编译器错误:
“CFString”类型的表达式模式不能匹配类型的值 'CFString字符串'
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
switch info[UIImagePickerControllerMediaType] as! CFString {
case kUTTypeImage:
break
default:
break
}
}
答案 0 :(得分:4)
我可以提出两种解决这种不便的方法。
简单,但需要额外输入。
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
switch info[UIImagePickerControllerMediaType] as! String {
case String(kUTTypeImage):
break
default:
break
}
}
更棘手,但如果您需要经常打开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
}
}