Lazy Var vs Let [英] Lazy Var vs Let

查看:49
本文介绍了Lazy Var vs Let的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对 Swift 中的一些属性使用延迟初始化.我当前的代码如下所示:

lazy var fontSize : CGFloat = {如果(某些情况){返回 CGFloat(30)} 别的 {返回 CGFloat(17)}}()

问题是,一旦设置了 fontSize,它就永远不会改变.所以我想做这样的事情:

lazy let fontSize : CGFloat = {如果(某些情况){返回 CGFloat(30)} 别的 {返回 CGFloat(17)}}()

这是不可能的.

仅此有效:

let fontSize : CGFloat = {如果(某些情况){返回 CGFloat(30)} 别的 {返回 CGFloat(17)}}()

所以 - 我想要一个延迟加载但永远不会改变的属性.这样做的正确方法是什么?使用 let 而忘记了懒惰的初始化?还是我应该使用 lazy var 而忘记属性的常量性质?

解决方案

这是来自 Xcode 6.3 Beta/Swift 1.2 发行说明:

<块引用>

let 常量已被概括为不再需要立即数初始化.新规则是 let 常量必须是在使用前初始化(如 var),并且它可能只是初始化:初始化后未重新分配或变异.

这会启用以下模式:

let x: SomeThing如果条件{x = foo()} 别的 {x = 条()}使用(x)

<块引用>

以前需要使用 var,即使没有发生突变.(16181314)

显然,您不是唯一对此感到沮丧的人.

I want to use Lazy initialization for some of my properties in Swift. My current code looks like this:

lazy var fontSize : CGFloat = {
  if (someCase) {
    return CGFloat(30)
  } else {
    return CGFloat(17)
  }
}()

The thing is that once the fontSize is set it will NEVER change. So I wanted to do something like this:

lazy let fontSize : CGFloat = {
  if (someCase) {
    return CGFloat(30)
  } else {
    return CGFloat(17)
  }
}()

Which is impossible.

Only this works:

let fontSize : CGFloat = {
  if (someCase) {
    return CGFloat(30)
  } else {
    return CGFloat(17)
  }
}()

So - I want a property that will be lazy loaded but will never change. What is the correct way to do that? using let and forget about the lazy init? Or should I use lazy var and forget about the constant nature of the property?

解决方案

This is the latest scripture from the Xcode 6.3 Beta / Swift 1.2 release notes:

let constants have been generalized to no longer require immediate initialization. The new rule is that a let constant must be initialized before use (like a var), and that it may only be initialized: not reassigned or mutated after initialization.

This enables patterns like:

let x: SomeThing
if condition {
    x = foo()
} else {
    x = bar()
}

use(x)

which formerly required the use of a var, even though there is no mutation taking place. (16181314)

Evidently you were not the only person frustrated by this.

这篇关于Lazy Var vs Let的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆