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.