变量/常数声明差异

时间:2015-09-12 23:31:23

标签: ios swift variables syntax semantics

哪些是最好的,这些声明中的任何一个本身都是多余的?

let imageView: UIImageView = UIImageView() // [1]
let imageView = UIImageView()              // [2]
let imageView: UIImageView!                // [3]
let imageView: UIImageView?                // [4]

1 个答案:

答案 0 :(得分:1)

您的示例也添加了一些评论。

  • 两种初始化方法
  • 声明可选
  • 的两种方法
  • 我还添加了后期初始化选项

Google可选项以获取更多信息。

// more text for more readability
let imageViewA: UIImageView = UIImageView() // [1]

// this is fine
let imageViewB = UIImageView()              // [2]

// this is danagerous
let imageViewC: UIImageView!                // [3]

// calling this before the next step will crash it
imageViewC.image = UIImage(data: NSData())

// it needs this step
imageViewC = UIImageView()

// this is fine because xcode will warn you when you are not handling it fine
let imageViewD: UIImageView?                // [4]

// it does needs this step
imageViewD = UIImageView()

// late init : this is cool stuff
let imageViewE: UIImageView

imageViewE = UIImageView()