Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add '/' -operator overloading to append a FilePath to another #179

Open
CodebyCR opened this issue May 18, 2024 · 0 comments
Open

Add '/' -operator overloading to append a FilePath to another #179

CodebyCR opened this issue May 18, 2024 · 0 comments

Comments

@CodebyCR
Copy link

CodebyCR commented May 18, 2024

Motivation

I write a CLI Tool and use some FilePath structs, but I think the current way to concatenated FilePaths is a way less readable & 'swifty' than it could be.
I remember the C++ 17 Filesystem Path Library which supports a overloading for the '/=' - operator to append a path to another.

The Swift FilePath Struct doesn't support any operator overloadings.
I think this possibility can smooth up the C++ Interoperability and make the syntax more readable.

The Problem in Code

    import System

    // Defined in another File for project configuration
    let homePath: FilePath = "/ProjectHome"
    let userDirectory: FilePath = "SomeUser"

    // The current ways

    // solution 1
    let userPath1 = FilePath("\(homePath)/\(userDirectory)")

    // solution 2
    let userPath2 = homePath.appending(userDirectory.components)

    // solution 3 (if userDirectory is a String)
    let userPath3 = homePath.appending(userDirectory)

Proposed solution

I wrote an extension to overload the '/' - operator. This also uses the 'appending' Function, but hides the superfluous syntax. So the path appending can be red like a Unix path.

The Extension

  public extension FilePath {
      static func / (firstPart: FilePath, pathPart: FilePath) -> FilePath {
          return firstPart.appending(pathPart.components)
      }
  }

Now I can write the path appending in this way:

Solution

  let userPath = homePath / userDirectory
  let userLogPath = homePath / userDirectory / "Logs"

Alternatives considered

An other approach would be the takeover of the C++ like '/='-operator overloading.

  var userPath = homePath
  userPath /= userDirectory

This isn't my preferred solution, because I think it isn't easier to read and this approach required a mutable FilePath struct.

Additional information

The URL could maybe also be extended in this way. Other Path-Based structs, classes also, but I don't know if it continues.

@Azoy Azoy transferred this issue from swiftlang/swift May 21, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant