I just begin to learn swift. And I have a question when I see a learning video. I have a screenshot. Why the variable "imageView1"can be referenced before the declaration statement..
is it right
That's what I explained:
In the code:
Class ViewController: UIViewController{
@IBAction func playButton(sender: UIButton){
imageView1.animationImages=[UIImage(named:”pad”)]
}
@IBOutlet weak var imageView1:UIImageView!
Line 6, you have defined imageView1 as an IBOutlet and connected to the object in IB (note the black dot on the left).
So, XCode automatically does the instantiation work to initialize imageView1.
That is a major interest of using storyboards.
Note a few point to fully understand:
- try to remove the connection of imageView1
- open the Connection inspector for the object in IB
- click the x in front of IBOutlet name in the connection inspector
- the black dot in code in front of line 6 becomes white, showing connection does not exist anymore
- try to run
- your app will crash
Reason is that now, object is not initilized !
- reconnect the object to its outlet
Second comment
Even though both ways work perfectly, it is a good practice to declare IBOutlets at the top :
Class ViewController: UIViewController{
@IBOutlet weak var imageView1:UIImageView!
@IBAction func playButton(sender: UIButton){
imageView1.animationImages=[UIImage(named:”pad”)]
}
}