2017-07-29 39 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)。 –