.Map producing [T] in Swift 3 after Converting from Swift 2

做~自己de王妃 提交于 2019-12-25 09:17:04

问题


I just converted a project from Swift 2 to Swift 3 and am getting an error, but I do not understand why the code is a problem:

var imagesInProject : NSArray?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
        print(paths[0])

        if let urls = Bundle.main.urls(forResourcesWithExtension: "png", subdirectory: nil) {
            imagesInProject = urls.filter {$0.lastPathComponent.hasPrefix("AppIcon") == false} .map {$0.lastPathComponent!}
        }

        return true

    }

The error is: "'map' produces '[T]', not the expected contextual result type 'NSArray?'"

How do I fix this? I'm familiar with .map but I don't totally understand the error or how the code is wrong (now)

Thanks!


回答1:


Implicit bridging to Foundation types has been removed from Swift 3. You are better off using native Swift types for your variables:

var imagesInProject : [URL]?

Or if you can't/don't want to do that for whatever reason, add an explicit cast:

imagesInProject = urls
                    .filter {$0.lastPathComponent.hasPrefix("AppIcon") == false}
                    .map {$0.lastPathComponent} as NSArray


来源:https://stackoverflow.com/questions/40686354/map-producing-t-in-swift-3-after-converting-from-swift-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!