0

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 !

2 Answers 2

3

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"]
Sign up to request clarification or add additional context in comments.

1 Comment

Yeah that's exactly what I was thinking reading the Swift guide about collection types 5 minutes ago, I didn't remember that arrays were type inferred, hence I need to specify the type of the empty array in order to modify it later. Thank you @eightx2 !
1

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)

1 Comment

Yeah, I read the guide right after posting my question and realized arrays where one-type collection objects, hence needing specifying the type for empty ones, since it cannot be inferred by Swift, thanks for your elaborate answer @Dev

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.