Skip to content

Instantly share code, notes, and snippets.

@tomkowz
Last active January 19, 2018 10:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomkowz/defec8de20950dbb5aa0 to your computer and use it in GitHub Desktop.
Save tomkowz/defec8de20950dbb5aa0 to your computer and use it in GitHub Desktop.
CustomStringConvertible
struct Position {
var x: Int = 0
var y: Int = 0
func string() -> String {
return "(\(x), \(y))"
}
}
// CustomStringConvertible provides "description" property.
// Before Xcode 7 beta 3 it was called "Printable" protocol.
// Using this protocol it cause that printing object under
// debugger will gives better description by default.
struct Position: CustomStringConvertible {
var x = 0
var y = 0
var description: String {
return "(\(x), \(y))"
}
}
@penangite
Copy link

penangite commented Jan 19, 2018

Hi. I am trying to look for clues as to how the computed property description is being called.

For example, using your code, I attempt to print the reference to the structure that I've created:

struct Position: CustomStringConvertible {
    var x = 0
    var y = 0
    
    var description: String {
        return "(\(x), \(y))"
    }
}

let position = Position()
print(position) // This should print "0, 0"

I'm just curious, how is the computed property description (implicitly) called?

Just to note, if I attempt the same on the structure that doesn't conform to the CustomStringConvertible protocol, the output is:
Position(x: 0, y: 0)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment