-
Notifications
You must be signed in to change notification settings - Fork 92
/
Contents.swift
58 lines (43 loc) · 1.01 KB
/
Contents.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
//: Playground - noun: a place where people can play
import UIKit
class ClosedRange{
let start: Int
let end: Int
var width: Int{
return end - start + 1
}
// 如果sum是computed property,每次调用都会计算
// var sum: Int{
// var res = 0
// for i in start...end{
// res += i
// }
// return res
// }
// 如果在init中计算,init太耗时
// var sum = 0
// 最佳方案,使用懒加载
lazy var sum: Int = {
//print("start computing sum value")
var res = 0
for i in self.start...self.end{
res += i
}
return res
}()
init?( start:Int , end:Int ){
if start > end{
return nil
}
self.start = start
self.end = end
// for i in start...end{
// sum += i
// }
}
}
if let range = ClosedRange(start: 0, end: 10_000){
range.width
range.sum
range.sum
}