2015-10-02 59 views
-1

为什么我会收到此错误?我粘贴代码,第一次尝试在运行时破坏了一个线程。天哪,我现在明白为什么第一个问题苹果的招聘人员问CS学生被你知道苹果的代码,或“迅速” ......(MEH)字符串不会转换为NSURL [SWIFT]

错误说 - lastPathComponent不可用:使用lastPathComponent上NSURL代替

// 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) 
     } 
    } 
+0

这是由于这样的事实,我是不能够使用原来的Xcode 5我部署在我的iPhone –

+0

感谢您的来信。这些应用程序是用Swift 1.2编写的,在Swift 1.2和Swift 2.0之间有许多突破性的变化。 Xcode 7需要Swift 2.0。 –

+0

您仍然可以在NSString中使用lastPathComponent。只需投(自我作为NSString).lastPathComponent或添加一个扩展到您的项目,所以你不需要改变你的代码在所有 –

回答

2

使用URL相关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!} 
} 
+0

nope。我试过了。并没有工作。 –

+0

'如果让路径= NSBundle.mainBundle()URLsForResourcesWithExtension( “PNG”,子目录:无)。{ //从路径 图像文件名对于在路径的路径为[AnyObject] { 如果path.lastPathComponent.hasPrefix! (“AppIcon”){ allCountries.append(path.lastPathComponent!) } } }' –

+0

不会转换为[AnyObject]。使用代码,因为它是 – vadian