How to change default inline string for custom structures and classes in Swift

Let's say I have a code structure:

struct Point {
  var x = 0.0
  var y = 0.0
}

var p = Point(x: 5.0, y: 3.0)
println("\(p)")

I will get:

V6<AppName>8Point (has 2 children)

Is there a way to convert this into something custom? In Objective-C, I believe this was covered by the method description(), but this does not work here.

+4
source share
3 answers

Yes, you can! Check out the Apple docs on the print protocol .

Example code from documents:

struct MyType: Printable {
    var name = "Untitled"
    var description: String {
        return "MyType: \(name)"
    }
}

let value = MyType()
println("Created a \(value)")
// prints "Created a MyType: Untitled"
+3
source

For everyone who came to this recently (Swift 2.0), the Printable protocol has been renamed to CustomStringConvertible

+3
source

You will need to implement the Printable protocol . Just make your class implement the protocol and add this property:

var description: String { get }
+1
source

Source: https://habr.com/ru/post/1543790/


All Articles