Files and Paths
Path Components
File URLs can expose the folder and file pieces of a path without opening the file.
Read path pieces
path_components.swift
Replay: real traced execution (multi-file project)
import Foundation
let path = "/docs/swift/guide.md"
let url = URL(fileURLWithPath: path)
let file = url.lastPathComponent
let folder = url.deletingLastPathComponent().lastPathComponent
let message = "\(folder)/\(file)"
print(message)
import Foundation
let path = "/tmp/report.txt"
let url = URL(fileURLWithPath: path)
let file = url.lastPathComponent
let folder = url.deletingLastPathComponent().lastPathComponent
let message = "\(folder)/\(file)"
print(message)
import Foundation
let path = "/lessons/intro.swift"
let url = URL(fileURLWithPath: path)
let file = url.lastPathComponent
let folder = url.deletingLastPathComponent().lastPathComponent
let message = "\(folder)/\(file)"
print(message)
path ← /docs/swift/guide.md, url ← file:///docs/swift/guide.md
3let path→ /docs/swift/guide.md = "/docs/swift/guide.md" //@path="/tmp/report.txt", "/lessons/intro.swift"4let url→ file:///docs/swift/guide.md = URL(fileURLWithPath: path/docs/swift/guide.md)5let file→ guide.md = url.lastPathComponentguide.md6let folder→ swift = url.deletingLastPathComponent().lastPathComponentswift7let message→ swift/guide.md = "\(folderswift)/\(fileguide.md)"89print(messageswift/guide.md)outputswift/guide.md
path ← /tmp/report.txt, url ← file:///tmp/report.txt, file ← report.txt
3let path→ /tmp/report.txt = "/tmp/report.txt"4let url→ file:///tmp/report.txt = URL(fileURLWithPath: path/tmp/report.txt)5let file→ report.txt = url.lastPathComponentreport.txt6let folder→ tmp = url.deletingLastPathComponent().lastPathComponenttmp7let message→ tmp/report.txt = "\(foldertmp)/\(filereport.txt)"89print(messagetmp/report.txt)outputtmp/report.txt
path ← /lessons/intro.swift, url ← file:///lessons/intro.swift
3let path→ /lessons/intro.swift = "/lessons/intro.swift"4let url→ file:///lessons/intro.swift = URL(fileURLWithPath: path/lessons/intro.swift)5let file→ intro.swift = url.lastPathComponentintro.swift6let folder→ lessons = url.deletingLastPathComponent().lastPathComponentlessons7let message→ lessons/intro.swift = "\(folderlessons)/\(fileintro.swift)"89print(messagelessons/intro.swift)outputlessons/intro.swift
path components
`lastPathComponent` reads the final path segment, while `deletingLastPathComponent` moves one level up.