一般来说,Swift中lazy定义计算属性的写法像下面这样,类似闭包的语法
1
2
3
4
5
|
lazy
var
players
:
[
String
]
=
{
var
temporaryPlayers
=
[
String
]
(
)
temporaryPlayers
.
append
(
"John Doe"
)
return
temporaryPlayers
}
(
)
|
或者实例方法
1
2
3
4
5
6
|
lazy
var
players
:
[
String
]
=
self
.
initialPlayers
(
)
func
initialPlayers
(
)
->
[
String
]
{
var
players
=
[
"John Doe"
]
return
players
}
|
或者类方法
1
2
3
4
5
6
7
8
9
|
class
TestClass
{
lazy
var
players
=
TestClass
.
initialPlayers
(
)
class
func
initialPlayers
(
)
->
[
String
]
{
var
players
=
[
"John Doe"
]
return
players
}
}
|
什么时候使用呢?
1. init初始化前,对象的属性还不知道的时候
2. 某个属性需要大量计算耗时,但是init对象的时候又不是必须用到这个属性的时候