无法将类型'[AnyObject]'的值赋给类型'[String]'Swift 2的值

时间:2015-08-29 11:09:11

标签: swift2

我尝试将我的项目从Swift更新为Swift 2,但是我收到以下代码的错误:

let PhotoController = UIImagePickerController() 
        PhotoController.delegate = self
        PhotoController.sourceType = UIImagePickerControllerSourceType.Camera 

        let mediaTypes:[AnyObject] = [kUTTypeImage] 

        PhotoController.mediaTypes = mediaTypes 

        PhotoController.allowsEditing  = false

        self.presentViewController(PhotoController, animated: true, completion: nil)

在以下行中:

PhotoController.mediaTypes = mediaTypes

编译器指出此错误:

  

不能将类型'[AnyObject]'的值赋给类型'[String]'的值

你能帮帮我吗? 非常感谢!

2 个答案:

答案 0 :(得分:7)

如果您确定数组类型为[String],则可以进行强制转换:

PhotoController.mediaTypes = mediaTypes as! [String]

否则我建议使用flatMap和每个对象的单独可选演员:

PhotoController.mediaTypes = mediaTypes.flatMap{ $0 as? String }

答案 1 :(得分:0)

只是我的猜测,但从文档判断 https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIImagePickerController_Class/#//apple_ref/occ/instp/UIImagePickerController/mediaTypes

尽管mediaTypes是[AnyObject],他们的示例中的Apple人员将其转换为[String](Obj-c上的示例!)

myImagePickerController.mediaTypes =
    [[NSArray alloc] initWithObjects: (NSString *) kUTTypeMovie, nil];

所以我会转换为String