Swift protocol for string interpolation

前端 未结 3 996
时光取名叫无心
时光取名叫无心 2021-02-20 00:19

What protocol do I have to implement to control the way an object is represented within a string interpolation in Swift?

I wan\'t to specify what get\'s printed in somet

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-20 00:55

    I would like to put an alternative solution here:

    The protocol for string interpolation in Swift is StringInterpolationConvertible. That is, any class which implements the protocol, can be constructed from a string interpolation.

    Back to the question, to control what is printed out for a String string interpolation of instances of class A, you would need to create a String extension and overload the init(stringInterpolationSegment expr: A) function.

    extension String {
        init(stringInterpolationSegment expr: A) {
            //do custom work here
            //for example: self.init(expr.description)
        }
    }
    

    In case you are looking for a way to remove the annoying "Optional(...)" when interpolating Optional variables, which I think is the main reason why people would want to control how an object gets printed out, just have a look at the pod NoOptionalInterpolation here.

    Additional information (edited): Confirm that overriding description will only work for your own struct/class, but not for existing struct/class such as Int and Optional.

提交回复
热议问题