#file behavior change in Swift 5.8
Table of Contents
Swift has many special literal expressions that can give metadata about your code.
For example:
#filePath
, which returns the path to the file it appears in.#line
returns the line number on which it appears.
These special literal expressions are useful for debugging purposes.
Before Swift 5.8, we have two special literal expressions that return the same thing, #file
and #filePath
.
Both of them will return the path to the file in which it appears.
print(#file)
// /Users/sarunw/Documents/MyProject/MyProject/ContentView.swift
print(#filePath)
// /Users/sarunw/Documents/MyProject/MyProject/ContentView.swift
Change in #file expression
In Swift 5.8, there is a behavior change for the #file
expression.
#file
will return the file name and the module in which it appears. And not including any path in it.
// Swift 5.8
print(#file)
// MyProject/ContentView.swift
// Before Swift 5.8
print(#file)
// /Users/sarunw/Documents/MyProject/MyProject/ContentView.swift
Caveat
As you might notice, this behavior change is considered a breaking change that impacts your code.
So, it means to be released in the future Swift 6.0.
In the meantime, this feature is disabled by default. You can opt into this new feature using a new Feature flag.
Add the following value to Other Swift Flags in Xcode to opt into this change.
-enable-upcoming-feature ConciseMagicFile
You can easily support sarunw.com by checking out this sponsor.
AI Grammar: Correct grammar, spell check, check punctuation, and parphrase.
Summary
You can think of #file
as an alias for other expressions.
- Before Swift 5.8,
#file
has the same behavior as#filePath
. - After Swift 5.8 (with ConciseMagicFile enabled) has the same behavior as
#fileID
.
So, if you want to be explicit about this behavior, you can also use #filePath
and #fileID
.
Literal | Before Swift 5.8 | Swift 5.8 with ConciseMagicFile enabled / Swift 6.0 |
---|---|---|
#file |
The path to the file in which it appears. (#filePath behavior) |
The name of the file and module in which it appears. (#fileID behavior) |
Read more article about Swift, Swift 5.8, or see all available topic
Enjoy the read?
If you enjoy this article, you can subscribe to the weekly newsletter.
Every Friday, you'll get a quick recap of all articles and tips posted on this site. No strings attached. Unsubscribe anytime.
Feel free to follow me on Twitter and ask your questions related to this post. Thanks for reading and see you next time.
If you enjoy my writing, please check out my Patreon https://www.patreon.com/sarunw and become my supporter. Sharing the article is also greatly appreciated.
Become a patron Buy me a coffee Tweet ShareHow to make Empty Space Tappable in SwiftUI
If you have ever added a tap gesture to a VStack or HStack, you might notice that space between content in a stack isn't tappable. Learn the reason and how to mitigate the problem.