Hardcoded Absolute Path
ID |
swift.hardcoded_absolute_path |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Swift |
Tags |
portability, reliability |
Description
Reports a string literal whose value looks like a Unix absolute
filesystem path (starts with / followed by an alphanumeric path
segment). Absolute paths break portability across devices, sandboxes,
and user accounts.
let cfg = "/etc/myapp/config" // FLAW
let dir = "/Users/alice/Documents" // FLAW
let cfg = Bundle.main.path(forResource: ...) // OK
let url = URL(string: "https://api.example.com") // OK — URL, not file path
let rel = "relative/path" // OK
Rationale
iOS / iPadOS / macOS apps run inside a per-app sandbox, so absolute
paths from the developer’s machine generally do not exist on a
user’s device. Even on Linux/server-side Swift, hard-coding paths
defeats user/admin configuration. The platform provides
Bundle, FileManager, and URL APIs that resolve location at
runtime relative to the right container.
Remediation
Use the platform path APIs:
let docs = FileManager.default.urls(
for: .documentDirectory, in: .userDomainMask
).first
let cfgURL = Bundle.main.url(forResource: "config", withExtension: "json")
For server-side code, take the root path from environment / config rather than coding it inline.