Member-only story
Using Swift’s CustomStringConvertible
A practical protocol
If you’d like to see a video version of this article, it’s right HERE
If you’re familiar with protocol
in Swift, you might be aware that either struct
value types or class
reference types can conform to them, and this can mean that there are some requirements you might need to meet or additional functionality is added to your conforming type.
One example might be if you have a User
struct:
struct User {
let name: String
let age: Int
}
which can be instantiated with the following type of expression:
let friend: User = User(name: "Karen", age: 32)
which can of course be printed to the console:
print (friend)
which prints this to the console: User(name: "Karen", age: 32)
.
Of course this is fine, but not exactly user-friendly (and you may well want such a thing to be visible to the end user at some point).
This is the default description of the type, but we can do better by supplying our own description, and doing better is something that we should always be aiming for in coding.