Swift变量初始化 [英] Swift Variables Initialization

查看:70
本文介绍了Swift变量初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于快速初始化变量的问题.

I have a question about variables initialization in swift.

我有两种方法来初始化变量(作为Objective-C中类的属性").

I have two ways to initialize a variable (as "property" of a class in Objective-C).

其中哪个是最正确的?

class Class {

  var label: UILabel!

  init() { ... label = UILabel() ... }

}

class Class {

  var label = UILabel()

  init() { … }

}

推荐答案

实际上,您有5种初始化属性的方法.

Actually you have 5 ways to initialize properties.

没有正确的方法,方法取决于需求.
基本上,尽可能将诸如 UILabel 之类的对象始终声明为常量( let ).

There is no correct way, the way depends on the needs.
Basically declare objects like UILabel always – if possible – as constant (let).

5种方法是:

  • 声明行中的初始化

  • Initialization in the declaration line

let label = UILabel(frame:...

  • init 方法中的初始化,您不必将属性声明为隐式未包装的可选内容.

  • Initialization in the init method, you don't have to declare the property as implicit unwrapped optional.

    let label: UILabel
    init() { ... label = UILabel(frame:...) ... }
    

  • 前两种方法实际上是相同的.

    The first two ways are practically identical.

    • 以类似 viewDidLoad 的方法进行初始化,在这种情况下,您必须将该属性声明为(隐式展开)可选,并且还声明为 var

    • Initialization in a method like viewDidLoad, in this case you have to declare the property as (implicit unwrapped) optional and also as var

    var label: UILabel!
    
    on viewDidLoad()
     ...
     label = UILabel(frame:...)
    }
    

  • 使用闭包进行初始化以分配默认(计算)值.初始化类后,将立即调用该闭包,并且无法在闭包中使用该类的其他属性.

  • Initialization using a closure to assign a default (computed) value. The closure is called once when the class is initialized and it is not possible to use other properties of the class in the closure.

    let label: UILabel = {
       let lbl = UILabel(frame:...)
       lbl.text = "Foo"
       return lbl
    }()
    

  • 使用闭包的惰性初始化.第一次访问该属性时,闭包被称为(一次),您可以使用该类的其他属性.
    该属性必须声明为 var

    let labelText = "Bar"
    
    lazy var label: UILabel = {
       let lbl = UILabel(frame:...)
       lbl.text = "Foo" + self.labelText
       return lbl
    }()
    

  • 这篇关于Swift变量初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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