简体   繁体   中英

SWIFT Xcode11.5 - array append not working in ViewController

Hi I'm trying to declare a simple array variable inside class ViewController. But when I try to append value to it, Xcode just keep giving me "Consecutive declarations on a line must be separated by ';'... Invalid redeclaration of 'mylist()'"

var mylist = [String] ()
mylist.append("abc")

I copied it into the Playground and it works just fine. But somehow inside ViewController it just doesn't like it. I only have 1 line that declares mylist in the whole project. Has any one experienced this? I can't see what's wrong with it. I'm in XCode 11.5(11E608c) Thx in advance.

Sorry I got it now.

The problem is inside class ViewController (or any class) you can declare the array variables but you can't append values into it until after the class is initialized.

So append will need to be done inside one of the class's func like func viewDidLoad().

Because at any other time the variable is NOT actually init yet and therefore can't be used.

And thus you can't execute its append function.

So I put the mylist.append("abc") inside func viewDidLoad now and it's all good.

Thank You.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM