The expected creation of an error error in the ViewController cannot decide why

Firstly, I use Xcode 6 beta 2. Secondly, I have programming experience (basic, VB, script), but it does not contain any serious OO programs, and I am completely unfamiliar with IOS programming. Go straight to Swift. Thanks in advance to those who can help. A few days later I fought for it.

Failed to create a simple UIImage array. (I just deleted all the other code). I'm trying to understand why declaring a UIImage array and loading images works in viewDidLoad (), but not in the "base" of the ViewController, where I seem to need this for other things to work.

(I noticed that this is because this is an array declaration, which confuses me with confusion. I can declare and assign simple UIImage variables at any location.)

Here is my code:

//  ViewController.swift


import UIKit

class ViewController: UIViewController {                           

    override func viewDidLoad() {

        super.viewDidLoad()

        // Do any additional setup after loading the view, typically from a nib.

    }



    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }

    var icon = UIImage[]()

    icon.append(UIImage(named: "yes.png"))    <<==== expected declaration error

    icon.append(UIImage(named: "no.png"))

}

But this code does not:

import UIKit
class ViewController: UIViewController {

     override func viewDidLoad() {

        super.viewDidLoad()

        // Do any additional setup after loading the view, typically from a nib.

        var icon = UIImage[]()

        icon.append(UIImage(named: "yes.png"))    <==== no error, and builds

        icon.append(UIImage(named: "no.png"))

    }


    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }

}
+4
source share
1 answer

You can only have property declarations outside the methods in the class. All class functionality is part of the methods. When you declare var icon = UIImage[]()outside a method, this is an instance property declaration and is valid code.

. , . , .

- , , . , , . iOS, objective-c, Swift, API Apple API, .

+9

Source: https://habr.com/ru/post/1546493/


All Articles