0

I have an object array like this:

private var _allusers = [Int:User]()

Here User is a custom class. Now, I am calling a PHP file and populating the _allusers object array the first time without any problem. However, I am running into problems IF I try to insert something at the beginning of the _allusers object array.

Generally, this is possible.

private var _intarray = [Int]()
self._intarray.insert(myObject, atIndex:0)

If I try to do the same for the object array I have then it doesn’t work.

self._allusers.insert(myObject, atIndex:0)

It gives me an error stating insert is not a function.

Can someone please help me with this? How can I insert an element at the beginning of the existing object array?

1
  • 1
    For starters, [Int:User] defines a dictionary, not an array. Commented Jun 28, 2016 at 15:37

2 Answers 2

3

The problem is that _allusers is not array, it is Dictionary (unordered type). Depending from what you need, you can use array of tuples for example:

private var _allusers = [(Int, User)]() // this is array
Sign up to request clarification or add additional context in comments.

3 Comments

Is there any way of inserting at the beginning of the dictionary since my dictionary index starts from 0 and increases sequentially?
Your question not have sense. Dictionary is unordered type. You can use array of tuples or of any else data structure if you wish.
@user3897036 Take a look at Collection Types in this Apple Document: developer.apple.com/library/ios/documentation/Swift/Conceptual/…
0

To expand on what Shadow Of is saying, in this case you seem to be stating that you want an array of Users indexed from 0 to N. What you are currently defining is a dictionary which indexes Users with arbitrary indexes over the entire range of Int, so you could have gaps users[0], users[3], users[8] without having users[1] or users[2]. If you truly have consecutive indices, just change your declaration to declare an array instead of a dictionary.

private var _allusers = [User]()

Now, _allusers is an array, the Users are indexed from 0..

_allusers.insert(newUser, atIndex:0)

Comments

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.