'swift default string interpolation for object [duplicate]
I've made an class - call it Blah. It contains a string "value". So anytime someone makes a string out of it - I want it to appear as the value. So I try it:
let x = Blah( "hello world")
XCTAassertEqual("hello world", "\(x)")
out of the box - of course it doesn't work - I haven't told it how to do the rendering. So I do some googling and find that thing is "description" - so add this to Blah:
public var description = {get{return _value}}
and then the test becomes this:
let x = Blah( "hello world")
XCTAassertEqual("hello world", "\(x.description)")
XCTAassertEqual("hello world", "\(x)")
the first assert works, but the second is still giving me the whole object
so - more googling - I find that you can add custom string interpolations.. so I add this:
extension String.StringInterpolation {
mutating func appendInterpolation(_ value: Blah) {
appendLiteral( value.description)
}
}
and that achieves... well... absolutely nothing. How do I change the way my objects are represented by string interpolation?
Solution 1:[1]
You were right about var description. However, you forgot to add the protocol CustomStringConvertible:
struct Blah {
let value: String
}
extension Blah: CustomStringConvertible {
var description: String { value }
}
let x = Blah(value: "Hello world")
print("Hello world: ", "\(x)")
Without the protocol, description is just a custom property.
Solution 2:[2]
I manage to get it to work.
class Blah {
let value: String
init(_ value: String) {
self.value = value
}
}
extension String.StringInterpolation {
mutating func appendInterpolation(_ value: Blah) {
appendLiteral(value.value)
}
}
func testBlah() {
let blah = Blah("Hello world")
XCTAssertEqual("Hello world", "\(blah)")
}
The test passes.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Sulthan |
| Solution 2 |
