Expected Declaration error creating array in ViewC

2019-01-15 15:57发布

First, I am using Xcode 6 beta 2. Second, I do have programming experience (basic, VB, script languages) ,but it doesnt include any serious OO programming, and I am totally new to IOS programming. Going straight into Swift. In advance, thanks to those who can help. I have been struggling over this a few days now.

Having trouble building a simple UIImage array. (I've stripped out all other code for simplicity.) I'm trying to understand why declaring an UIImage array and loading images works within viewDidLoad(), but not at the "base" of ViewController, which is where I seem to need it for other things to work.

(I've noticed it seems to be tied into the fact that this is an array declaration, which futhers my confusion. I can declare and assign simple UIImage variables in either location.)

Here's 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.

    }

}

1条回答
爷的心禁止访问
2楼-- · 2019-01-15 16:22

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

Your next two lines attempt to modify the property. Code outside of methods is never executed because there is no way to call it. While you can declare properties outside of methods, you have to use them inside a method in your class.

I'd recommend learning more about Object Oriented programming, because it seems like you don't quite have the grasp of it yet. You may want to try a language that has more reliability and learning resources than swift currently does. If you are planning on doing iOS development, it would be helpful to learn objective-c even if you want to use Swift because you'll gain exposure to Apple's APIs which are the same in both languages.

查看更多
登录 后发表回答