2015-10-02 60 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