title: Calculating if CGPoint is on a line segment?
body: <p>I'm looking for a way to calculate if a CGPoint is on a line segment. Are there any built-in methods in Swift or any of Apple's libraries?</p>
  <p>I don't mind converting to a different type as long as it is part of Apple's code (e.g. similar to how <a href="https://medium.com/@norling.samuel/arkit-dont-read-the-transform-1ab771f49e64" rel="nofollow noreferrer">instead of performing complex calculations on double4x4 matrix, you can convert it to an SCNNode</a>).</p>
  <hr />
  <p>I quickly came up with brute force solution, but it's neither elegant, nor accurate (given floating point comparisons everywhere):</p>
  <pre><code>extension CGPoint {
    func isOnLineSegment(start: CGPoint, end: CGPoint) -&gt; Bool {
      func value(_ value: CGFloat, isBetween one: CGFloat, and two: CGFloat) -&gt; Bool {
        let a = [one, two].sorted()
        return a[0] &lt;= value &amp;&amp; value &lt;= a[1]
      }
  
      let slope = (end.y - start.y) / (end.x - start.x)
      if slope.isInfinite {
        let isOnLine = x.isNearlyEqual(to: start.x)
        let isWithinYValues = value(y, isBetween: start.y, and: end.y)
        return isOnLine &amp;&amp; isWithinYValues
      }
  
      let isOnLine = y.isNearlyEqual(to: slope * (x - start.x) + start.y) // y = m * (x - x1) + y1
      let isWithinXValues = value(x, isBetween: start.x, and: end.x)
  
      return isOnLine &amp;&amp; isWithinXValues
    }
  }
  </code></pre>