Orkhan Alikhanov
Orkhan Alikhanov

Reputation: 10050

NSString.appendingPathComponent(_:) not working correctly on Linux

Apple's documentation of the NSString.appendingPathComponent(_:) describes:

The method works as expected on macOS but fails on linux. Is there any workaround? Is this a feature or bug? Where can we report this?

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")) 

Upvotes: 1

Views: 385

Answers (1)

Code Different
Code Different

Reputation: 93181

It's definitely a bug, since it runs counter to the documentation. One of them needs to be fixed and I think it's the code. Open a new bug here.

With Swift, Apple removed all these path APIs from String, which has been a poor fit in my opinion. Apple's preferred method to do path manipulation is with 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)

The last line behaves differently from NSString. It appends scratch.tiff to the current directory. In other word, it's expanded form of ./scratch.tiff

Upvotes: 2

Related Questions