Vincent Rolea
Vincent Rolea

Reputation: 1663

Creating and populating an empty Array

I'm actually learning swift in order to develop iOS apps. I'd like, as an exercise, to create and populate an empty array, that would be filled by using a textfield and a button on the storyboard.

var arr = []

// When button is pressed : 
arr.append(textfield.text)

XCode tells me that the append method is not a method of NSArray. So I have used the addObject one, but it is still not correct as the arr variable contains nil.

So here are my three questions :

Is it possible to create an empty array, and if so, how to populate it ?

Sometimes, in my ViewController, when I create a non-empty array, the append method is apparently not valid, and I don't understand why..

Finally, why even though I use the syntax :

var arr = [1] // For example

The arr object is NSArray object and not a NSMutableArray object, making it impossible to add/remove any object that is contained in it?

I hope my questions are clear, if not I'll upload more code of what I'm trying to build,

thank you for your answers !

Upvotes: 0

Views: 2230

Answers (2)

Dev
Dev

Reputation: 1213

Empty array can be created using the following syntax.

var emptyArray = [String]()
emptyArray.append("Hi")

see this

You can use following also to add elements to your array.

//append - to add only one element
emptyArray.append("Hi")

//To add multiple elements
emptyArray += ["Hello", "How r u"]
emptyArray.extend(["am fine", "How r u"])

//Insert at specific index
emptyArray.insert("Who r u", atIndex: 1)

//To insert another array objects
var array1 = ["who", "what", "why"]
emptyArray.splice(array1, atIndex: 1)

Upvotes: 1

gosr
gosr

Reputation: 4708

Try to define your array as a String array, like this:

var arr: [String] = []

And then append to your list, either by:

arr.append("the string")

or

arr += ["the string"]

Upvotes: 3

Related Questions