UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Concise magic file names

Available from Swift 5.8

Paul Hudson      @twostraws

SE-0274 adjusts the #file magic identifier to use the format Module/Filename, e.g. MyApp/ContentView.swift. Previously, #file contained the whole path to the Swift file, e.g. /Users/twostraws/Desktop/WhatsNewInSwift/WhatsNewInSwift/ContentView.swift, which is unnecessarily long and also likely to contain things you’d rather not reveal.

Important: Right now this behavior is not enabled by default. SE-0362 adds a new -enable-upcoming-feature compiler flag designed to let developers opt into new features before they are fully enabled in the language, so to enable the new #file behavior you should add -enable-upcoming-feature ConciseMagicFile to Other Swift Flags in Xcode.

If you’d like to have the old behavior after this flag is enabled, you should use #filePath instead:

// New behavior, when enabled
print(#file)

// Old behavior, when needed
print(#filePath)

The Swift Evolution proposal for this change is worth reading because it mentions surprisingly large improvements in binary size and execution performance, and also for this quite brilliant paragraph explaining why having the full path is often a bad idea:

“The full path to a source file may contain a developer's username, hints about the configuration of a build farm, proprietary versions or identifiers, or the Sailor Scout you named an external disk after.”

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Other changes in Swift 5.8…

Download all Swift 5.8 changes as a playground Link to Swift 5.8 changes

Browse changes in all Swift versions

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.