Search code examples
swiftcustomstringconvertible

Why CustomStringConvertible protocol description being called multiple times?


I have written a struct in iOS playground and want to customize the print format of it.

struct Point {
    let x: Int, y: Int
}

extension Point: CustomStringConvertible {
    var description: String {
       switch (x, y) {
       case let (x, 1..<10):
          print("y in the range")
          return "(\(x), 1..<10)"
       default:
          return "(\(x), \(y))"
      }
   }
}

let p = Point(x: 1, y: 1)
print(p)

The result is

enter image description here

I cannot understand that even though I called print only once but y in the range message is being printed 4 times.


Solution

  • If you're using a playground, the description of a value may be computed multiple times because it will be shown in multiple places (e.g. on the right).

    If you're executing the code in a more controlled environment (like in compiled code or in the REPL in a terminal), you will notice that y in the range will only be printed once.

    Also you should avoid side effects (like print statements) in computed properties.