2

#file behavior change in Swift 5.8

 11 months ago
source link: https://sarunw.com/posts/file-behavior-change/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

#file behavior change in Swift 5.8

15 May 2023 ⋅ 2 min read ⋅ Swift 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
-enable-upcoming-feature ConciseMagicFile

-enable-upcoming-feature ConciseMagicFile

You can easily support sarunw.com by checking out this sponsor.

Glassfy:

Sponsor sarunw.com and reach thousands of iOS developers.

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)

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK