Files and Paths
Joining Paths
Appending a component builds a new path without manually placing slashes.
Append a file name
joining_paths.swift
Replay: real traced execution (multi-file project)
import Foundation
let fileName = "intro.md"
let folder = "/docs/swift"
let url = URL(fileURLWithPath: folder).appendingPathComponent(fileName)
let message = url.path
print(message)
import Foundation
let fileName = "setup.md"
let folder = "/docs/swift"
let url = URL(fileURLWithPath: folder).appendingPathComponent(fileName)
let message = url.path
print(message)
import Foundation
let fileName = "chapter1.md"
let folder = "/docs/swift"
let url = URL(fileURLWithPath: folder).appendingPathComponent(fileName)
let message = url.path
print(message)
fileName ← intro.md, folder ← /docs/swift, url ← file:///docs/swift/intro.md
3let fileName→ intro.md = "intro.md" //@fileName="setup.md", "chapter1.md"4let folder→ /docs/swift = "/docs/swift"5let url→ file:///docs/swift/intro.md = URL(fileURLWithPath: folder/docs/swift).appendingPathComponent(fileNameintro.md)6let message→ /docs/swift/intro.md = url.path/docs/swift/intro.md78print(message/docs/swift/intro.md)output/docs/swift/intro.md
fileName ← setup.md, folder ← /docs/swift, url ← file:///docs/swift/setup.md
3let fileName→ setup.md = "setup.md"4let folder→ /docs/swift = "/docs/swift"5let url→ file:///docs/swift/setup.md = URL(fileURLWithPath: folder/docs/swift).appendingPathComponent(fileNamesetup.md)6let message→ /docs/swift/setup.md = url.path/docs/swift/setup.md78print(message/docs/swift/setup.md)output/docs/swift/setup.md
fileName ← chapter1.md, folder ← /docs/swift, url ← file:///docs/swift/chapter1.md
3let fileName→ chapter1.md = "chapter1.md"4let folder→ /docs/swift = "/docs/swift"5let url→ file:///docs/swift/chapter1.md = URL(fileURLWithPath: folder/docs/swift).appendingPathComponent(fileNamechapter1.md)6let message→ /docs/swift/chapter1.md = url.path/docs/swift/chapter1.md78print(message/docs/swift/chapter1.md)output/docs/swift/chapter1.md
path joining
`appendingPathComponent` adds one path segment and keeps the separator rules in one place.