How can I change the textual representation displayed for a type in Swift?

后端 未结 6 925
广开言路
广开言路 2020-11-29 21:07

How can I modify the textual output that gets displayed in string interpolation?

The Printable protocol looks the most obvious but it\'s ignored in both

6条回答
  •  情歌与酒
    2020-11-29 21:23

    As an alternative in Swift 5+ you can extend the String.StringInterpolation

    struct Point {
        var x : Int
        var y : Int
    }
    
    extension String.StringInterpolation {
        mutating func appendInterpolation(_ value: Point) {
            appendInterpolation("\(value.x):\(value.y)")
        }
    }
    

    This will change the value for print("\(p)") but not for print(p) - which will still use the description

提交回复
热议问题