Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change default embedded string for custom structs and classes in Swift

Tags:

swift

Say I have a code struct of:

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 anyway to convert this into something custom? In Objective-C I believe this was covered with the description() method, but that isn't working here.

like image 998
Ryan Avatar asked Mar 19 '23 09:03

Ryan


1 Answers

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

Example code from the docs:

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

let value = MyType()
println("Created a \(value)")
// prints "Created a MyType: Untitled"
like image 190
Cezary Wojcik Avatar answered Apr 08 '23 07:04

Cezary Wojcik