-2

I am learning about Swift extensions, and wrote a simple extension to Double in a Playground. Code is below.

extension Double {          
    func round(to places: Int) -> Double {
        let precisionNumber = pow(10, Double(places))
        var n = self        //self contains the value of the myDouble variable
        n = n * precisionNumber
        n.round()
        n = n / precisionNumber
        return n
    }
}

var myDouble = 3.14159
myDouble.round(to: 1)

The extension works as planned, however when I press "show result" (the eye icon) in the right column for any line of code in the extension, I see a horizontal line.

enter image description here

Anyone know what this line is supposed to signify? Using Xcode 11.2.1 and Swift 5.

JMBaker
  • 502
  • 3
  • 7
  • It’s called a graph. Plots a sequence of values. This one shows two points, corresponding to the “two times” in the result column. – matt Dec 08 '19 at 10:05
  • Ok, thanks for your answer. But I still don't know how I'm supposed to use this graph. How does this help me as the developer? – JMBaker Dec 08 '19 at 11:15
  • It’s not much use in your code, but in a deliberate loop it’s nice to see some representation of all the values. https://indiestack.com/2018/02/playground-graphs/ – matt Dec 08 '19 at 17:49

1 Answers1

0

The trouble here is that you have not revealed all of your playground. My guess is that there is more code, where you call your extension again. Perhaps your real code looks something like this:

extension Double {
    func round(to places: Int) -> Double {
        let precisionNumber = pow(10, Double(places))
        var n = self        //self contains the value of the myDouble variable
        n = n * precisionNumber
        n.round()
        n = n / precisionNumber
        return n
    }
}

var myDouble = 3.14159
myDouble.round(to: 1) // once
print(myDouble)

myDouble = myDouble.round(to: 1) // twice; in your case it's probably another value
print(myDouble)

That is a very poor way to write your playground, if your goal is to write and debug your extension, for the very reason you have shown. You have called the extension two times, so what meaningful value can be shown as the "result" of each line of the extension? The playground has to try to show you both "results" from both calls. The only way it can think of to do that is to graph the two results.

That is a downright useful representation, though, when you are deliberately looping or repeating code, because you get at least a sense, through the graph, of how the value changes each time thru the loop.

matt
  • 515,959
  • 87
  • 875
  • 1,141