0

Which of those is best and is any of these declarations per se redundant?

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

1 Answers1

1

Added some comments too your examples.

  • two ways to init
  • two ways to declare an optional
  • I also added the late init option

Google optionals for more info.

// 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()
R Menke
  • 8,183
  • 4
  • 35
  • 63