user3246092 user3246092 - 1 year ago 296
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)

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)


Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download