Skip to content

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

@CodebyCR

Description

@CodebyCR

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions