how to make a custom struct behave like a string ?
Asked on 03/24/2025
1 search
To make a custom struct behave like a string in Swift, you can conform your struct to the CustomStringConvertible
protocol. This protocol requires you to implement a description
property, which returns a String
representation of your struct. This allows your struct to be used in contexts where a String
is expected, such as printing or string interpolation.
Here's a basic example:
struct MyStruct: CustomStringConvertible {
var property1: String
var property2: Int
var description: String {
return "MyStruct(property1: \(property1), property2: \(property2))"
}
}
let myStruct = MyStruct(property1: "Hello", property2: 42)
print(myStruct) // Output: MyStruct(property1: Hello, property2: 42)
This approach is similar to the concept of providing custom test descriptions mentioned in the Go further with Swift Testing session, where you can make your type conform to a protocol to provide a concise description without affecting production code.

Explore Swift performance
Discover how Swift balances abstraction and performance. Learn what elements of performance to consider and how the Swift optimizer affects them. Explore the different features of Swift and how they’re implemented to further understand the tradeoffs available that can impact performance.

Build multilingual-ready apps
Ensure your app works properly and effectively for multilingual users. Learn best practices for text input, display, search, and formatting. Get details on typing in multiple languages without switching between keyboards. And find out how the latest advances in the String Catalog can make localization even easier.

Migrate your app to Swift 6
Experience Swift 6 migration in action as we update an existing sample app. Learn how to migrate incrementally, module by module, and how the compiler helps you identify code that’s at risk of data races. Discover different techniques for ensuring clear isolation boundaries and eliminating concurrent access to shared mutable state.