【问题标题】:.Map producing [T] in Swift 3 after Converting from Swift 2.Map 从 Swift 2 转换后在 Swift 3 中生成 [T]
【发布时间】:2016-11-18 21:40:27
【问题描述】:

我刚刚将一个项目从 Swift 2 转换为 Swift 3 并收到错误,但我不明白为什么代码有问题:

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

    }

错误是:“'map' 产生 '[T]',而不是预期的上下文结果类型 'NSArray?'”

我该如何解决这个问题?我对 .map 很熟悉,但我不完全理解错误或代码是如何错误的(现在)

谢谢!

【问题讨论】:

  • 不要使用NSArray,使用实际类型化的swift数组

标签: ios iphone swift xcode swift3


【解决方案1】:

到 Foundation 类型的隐式桥接是 removed from Swift 3。最好为变量使用原生 Swift 类型:

var imagesInProject : [URL]?

或者,如果您出于某种原因不能/不想这样做,请添加明确的演员表:

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

【讨论】:

  • 抛出错误,除非'!'已从 lastPathComponent 中删除——我无法编辑它,因为它不到六个字符
猜你喜欢
  • 2017-02-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-07
  • 1970-01-01
  • 2017-11-27
相关资源
最近更新 更多