字符串未转换为NSURL [SWIFT]

时间:2015-10-02 18:29:30

标签: ios iphone swift nsurl

为什么我收到此错误?我粘贴代码,我的第一次尝试在运行时打破了一个线程。天哪,现在我明白为什么苹果招聘人员问CS学生的第一个问题是你知道苹果代码,还是“快速......”(meh)

错误说 - lastPathComponent不可用:改为使用NSURL上的lastPathComponent

    // get a list of all the png files in the app's images group
    let paths = NSBundle.mainBundle().pathsForResourcesOfType(
        "png", inDirectory: nil) 

    // get image filenames from paths
    for path in paths  {
        if !path.lastPathComponent.hasPrefix("AppIcon") { //error
            allCountries.append(path.lastPathComponent)  //error
        }
    }

尝试1:

    for path in paths as [AnyObject] {
        if !path.lastPathComponent.hasPrefix("AppIcon") {
            allCountries.append(path.lastPathComponent)
        }
    }

1 个答案:

答案 0 :(得分:2)

使用与网址相关的API

if let imageURLs = NSBundle.mainBundle().URLsForResourcesWithExtension("png", subdirectory: nil) {
  // get image filenames from paths
  for url in imageURLs  {
    if !url.lastPathComponent!.hasPrefix("AppIcon") {
      allCountries.append(url.lastPathComponent!)
    }
  }
}

或者有点“Swiftier”

if let urls = NSBundle.mainBundle().URLsForResourcesWithExtension("png", subdirectory: nil) {
  allCountries = urls.filter {$0.lastPathComponent!.hasPrefix("AppIcon") == false} .map {$0.lastPathComponent!}
}