Better print for AnyKeyPath in Swift 5.8
Table of Contents
Before Swift 5.8, if you try to print a keypath via a print()
or po
command, it will print out general output for a Swift class.
struct User {
let firstName: String
let lastName: String
var nickName: String
}
print(\User.firstName)
// Swift.KeyPath<ModuleName.User, Swift.String>
print(\User.lastName)
// Swift.KeyPath<ModuleName.User, Swift.String>
print(\User.nickName)
// Swift.WritableKeyPath<ModuleName.User, Swift.String>
In this example, Swift will print a class name and a type of that key path.
This isn't very useful since you can't distinguish one property from another.
You can easily support sarunw.com by checking out this sponsor.
Offline Transcription: Fast, privacy-focus way to transcribe audio, video, and podcast files. No data leaves your Mac.
Add CustomDebugStringConvertible conformance to AnyKeyPath
Swift 5.8 ([SE-0369]) make AnyKeyPath
conform to CustomDebugStringConvertible
protocol and provide more useful information when print.
The followings are the output for the same keypaths.
print(\User.firstName)
// \User.firstName
print(\User.lastName)
// \User.lastName
print(\User.nickName)
// \User.nickName
As you can see, we know at a glance what the keypaths are referring to.
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 convert Radians to Degrees in Swift
In this article, we will learn different ways to convert Radians to Degrees in iOS.
How to convert between NSAttributedString and AttributedString
SwiftUI lacks the support for the old NSAttributedString but fully supports this new type. On the other hand, UIKit supported NSAttributedString but lacked the support of AttributedString in most APIs. Learn how to convert between the two, so you can use any of them in the platform you want.