Garret Kaye
Garret Kaye

Reputation: 2562

can you have an array with no element at index 0

Im wondering if it is possible to insert an element at index 1 but not index 0 in swift like this:

            var array = [String]()

            array.insert("cow", atIndex: 1)

but every time I try I get the old fatal error: Array index out of range error message.

Is there anyway around this problem? Any suggestions would be greatly appreciated! Thanks!

Upvotes: 0

Views: 398

Answers (4)

Mr Beardsley
Mr Beardsley

Reputation: 3863

If you really want the index to be specific, rather than just the next available position in the array, you should use a dictionary with Int keys.

var dict = [Int:String]()
dict[1] = "Cow"
dict[5] = "Chicken"

Upvotes: 2

vadian
vadian

Reputation: 285170

Literally you can't.

An item can be inserted up to the maximum index index(max) = array.count, in case of an empty array at index 0.

Upvotes: 0

Phillip Mills
Phillip Mills

Reputation: 31016

If you make it an array of optionals and initialize the number of elements you want first, you can get close.

var array = [String?]()
for i in 0...5 {
    array.append(nil)
}

array.insert("cow", atIndex: 1)

Upvotes: 2

Stephen Brickner
Stephen Brickner

Reputation: 2602

You can create a custom list. You will need to add some checking to make sure items aren't null or out of index, etc.

void Main()
{
    var list = new CustomList<string>();
    list.Add("Chicken");
    list.Add("Bear");

    list[1] = "Cow";

    list[1].Dump(); //output Cow
}

public class CustomList<T>
{
    IList<T> list = new List<T>();

    public void Add(T item)
    {
        list.Add(item);
    }

    public T this[int index]
    {
       get
       {
           return list[index - 1];
       }
       set
       {
            list[index - 1] = value;
       }
    }
}

Upvotes: 0

Related Questions