Skip to content

Instantly share code, notes, and snippets.

@totiz
Last active May 23, 2016 09:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save totiz/f30859af8927e427b210f4308a33eb2c to your computer and use it in GitHub Desktop.
Save totiz/f30859af8927e427b210f4308a33eb2c to your computer and use it in GitHub Desktop.
Lazy Line 1
//: Playground - noun: a place where people can play
import UIKit
struct Line {
let begin: CGPoint
let end: CGPoint
init(begin: CGPoint, end: CGPoint) {
self.begin = begin
self.end = end
}
// คำนวณระยะทางครั้งเดียว ในครั้งแรกที่เรียก
lazy var length: CGFloat = {
return CGFloat(hypotf(Float(self.end.x - self.begin.x), Float(self.end.y - self.begin.y)))
}()
}
// Example
var line = Line(begin: CGPoint(x: 12, y: 12), end: CGPoint(x: 20, y: 20))
print(line.length) // คำนวณระยะทาง เพราะเรียกใช้ครั้งแรก
print(line.length) // แสดงระยะทางจากที่คำนวณไว้แล้ว ไม่ต้องคำนวณใหม่
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment