如何在 UIImagePickerController MediaType 上使用 switch 语句?
How to use the switch statement on UIImagePickerControllerMediaType?
如何在 UIImagePickerControllerMediaType
上使用 switch 语句?
以下示例抛出奇怪的编译器错误:
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
}
}
我可以建议两种方法来解决这个不便。
转换为字符串
简单,但需要额外输入。
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
}
参见语言参考 (Swift 2.2) Patterns 章节中的 "Expression Pattern" 部分。
解决此问题的另一种方法是转换为 NSString
:
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
switch info[UIImagePickerControllerMediaType] as! NSString {
case kUTTypeImage:
break
default:
break
}
}
如何在 UIImagePickerControllerMediaType
上使用 switch 语句?
以下示例抛出奇怪的编译器错误:
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
}
}
我可以建议两种方法来解决这个不便。
转换为字符串
简单,但需要额外输入。
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
}
参见语言参考 (Swift 2.2) Patterns 章节中的 "Expression Pattern" 部分。
解决此问题的另一种方法是转换为 NSString
:
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
switch info[UIImagePickerControllerMediaType] as! NSString {
case kUTTypeImage:
break
default:
break
}
}