classNetworkManager { lazyvar urlSession: URLSession= { let configuration =URLSessionConfiguration.default let urlSession =URLSession(configuration: configuration) return urlSession }()
// ... }
lazy 为 Swift 中的关键字,可以用于类和结构体的存储变量属性,表示该属性只在首次进行访问时初始值才会计算和存储。
需要注意的是:
If a property marked with the lazy modifier is accessed by multiple threads simultaneously and the property has not yet been initialized, there is no guarantee that the property will be initialized only once. 如果标记有 lazy 修饰符的属性同时被多个线程访问,并且该属性尚未初始化,则不能保证该属性仅被初始化一次。
Global constants and variables are always computed lazily, in a similar manner to Lazy Stored Properties. Unlike lazy stored properties, global constants and variables do not need to be marked with the lazy modifier. 全局常量和变量总是延迟计算,与惰性存储属性类似的方式。与惰性存储的属性不同的是,全局常量和变量不需要使用 lazy 修饰符进行标记。
Local constants and variables are never computed lazily. 局部常量和变量永远不会延迟计算。