2017-07-29 33 views
0
正常工作

蘋果公司NSString.appendingPathComponent(_:)的文檔描述: NSString.appendingPathComponent(_ :)不是在Linux上

的方法將按預期在MacOS但沒有在Linux上。有什麼解決方法嗎?這是一個功能還是錯誤?我們可以在哪裏報告?

Run online

import Foundation 


extension String { 
    func appendingPathComponent(_ str: String) -> String { 
     return NSString(string: self).appendingPathComponent(str) 
    } 
} 

// prints correctly: "/tmp/scratch.tiff" 
print("/tmp".appendingPathComponent("scratch.tiff")) 

// should print: "/tmp/scratch.tiff" but prints "/tmp//scratch.tiff" 
print("/tmp/".appendingPathComponent("scratch.tiff")) 

// prints correctly: "/scratch.tiff" 
print("/".appendingPathComponent("scratch.tiff")) 

// should print: "scratch.tiff" but prints "/scratch.tiff" 
print("".appendingPathComponent("scratch.tiff")) 

回答

2

這絕對是一個錯誤,因爲它違背了文檔。其中一個需要修復,我認爲這是代碼。打開一個新的錯誤here

使用Swift,Apple從String中刪除了所有這些路徑API,這在我看來一直不太合適。蘋果公司做的一個路徑處理較好的方法是用URL

print(URL(fileURLWithPath: "/tmp").appendingPathComponent("scratch.tiff").path) 
print(URL(fileURLWithPath: "/tmp/").appendingPathComponent("scratch.tiff").path) 
print(URL(fileURLWithPath: "/").appendingPathComponent("scratch.tiff").path) 
print(URL(fileURLWithPath: "").appendingPathComponent("scratch.tiff").path) 

最後一行從NSString表現不同。它將scratch.tiff附加到當前目錄。換言之,它的擴展形式爲./scratch.tiff

+0

感謝您的回答。我剛剛提交了一個[bug報告](https://bugs.swift.org/browse/SR-5582)。 –