Tony Chan
Tony Chan

Reputation: 9

Why array's append method cannot be used in viewController?

I am beginner of swift. I tried to use array's append method in my code but it doesn't work. How should I implement the array correctly?

The error messages: Swift Compiler Error Group ViewController.swift:16:5: Expected declaration ViewController.swift:11:7: In declaration of 'ViewController'

I tried to use array's append method in my code but it doesn't work.

import UIKit

class ViewController: UIViewController { //Error msg: In declaration of 'ViewController'

@IBOutlet weak var dice: UIImageView!
@IBOutlet weak var dice2: UIImageView!
var dices : [String] = []
dices.append("Hi") //Error: Expected declaration

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

@IBAction func rollPressed(_ sender: UIButton) {
    dice.image = UIImage(named: "dice3")
}

}

I expect I can add "hi" into the array dices.

Upvotes: 0

Views: 94

Answers (2)

cookednick
cookednick

Reputation: 1088

SH_Khan is right. I'll explain why though.

When defining a class, the first level of indentation is only for its methods and properties, aka func, var, and let. (You can also define other classes/structs/enums in there too)

Calling those functions or system functions like Array.append() or print("dog sweat") must happen inside of another function. The reason why is that your application's live logic is literally just functions all the way down. No function gets called unless it's inside of another function first. (The only exceptions are Swift's quick and dirty initializations like setting a default value to a var outside of an init() { } or another function.)

A dog doesn't wake up from its nap unless you make some noise. It won't do it on its own. (crappy metaphor, but yeah)

I hope that made any sense.

Upvotes: 1

Shehata Gamal
Shehata Gamal

Reputation: 100549

You should call the append inside a function after the vc is fully initated

class ViewController: UIViewController { //Error msg: In declaration of 'ViewController'

@IBOutlet weak var dice: UIImageView!
@IBOutlet weak var dice2: UIImageView!
var dices : [String] = [] 

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    dices.append("Hi") // e.x here
}

@IBAction func rollPressed(_ sender: UIButton) {
    dice.image = UIImage(named: "dice3")  
}

}

Or replace

var dices : [String] = []

with

var dices = ["Hi"]

Upvotes: 3

Related Questions