Using Swift’s CustomStringConvertible

A practical protocol

Photo by Hermes Rivera on Unsplash
struct User {
let name: String
let age: Int
}
let friend: User = User(name: "Karen", age: 32)

Conforming to CustomStringConvertable

Conforming to CustomStringConvertable is a reasonably easy task if you are familiar with conforming to a protocol

struct User: CustomStringConvertible {
let name: String
let age: Int
}
Type 'User' does not conform to protocol 'CustomStringConvertible'
struct User: CustomStringConvertible {
var description: String {
return "\(name) is \(age)"
}

let name: String
let age: Int
}

let friend: User = User(name: "Karen", age: 32)
print(friend)

Conforming to protocol

This is a common thing in Swift. To make code easier to read we place the conformance for protocols into an extension. This is because this makes it easier to read for other people using your code:

struct User {
let name: String
let age: Int
}

extension User: CustomStringConvertible {
var description: String {
return "\(name) is \(age)"
}
}

let friend: User = User(name: "Karen", age: 32)
print(friend)

Conclusion

Conforming to CustomStringConvertible is a common thing we might do in Swift - but when we do it is important to get it right.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store