user3246092 user3246092 - 21 days ago 28
iOS Question

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

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!

Answer

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