【问题标题】:can you have an array with no element at index 0你能有一个在索引 0 处没有元素的数组吗
【发布时间】:2016-02-12 23:21:20
【问题描述】:

我想知道是否可以像这样在索引 1 处插入一个元素,但不能在索引 0 处插入一个元素:

            var array = [String]()

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

但每次我尝试都会收到旧的致命错误:数组索引超出范围错误消息。

有没有解决这个问题?任何建议将不胜感激!谢谢!

【问题讨论】:

  • 我的第一反应是你应该重新考虑你的架构。我可能是错的,但你认为你需要这样做的事实可能是一种不好的气味。为什么你需要做这样的事情?

标签: arrays swift indexing


【解决方案1】:

您可以创建自定义列表。您将需要添加一些检查以确保项目不为空或超出索引等。

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;
       }
    }
}

【讨论】:

    【解决方案2】:

    如果你把它做成一个可选数组,并先初始化你想要的元素数量,你就可以接近了。

    var array = [String?]()
    for i in 0...5 {
        array.append(nil)
    }
    
    array.insert("cow", atIndex: 1)
    

    【讨论】:

    • 该死的,这是个好主意。我从来没有想过这个!谢谢!
    • 也许您甚至可以将其实现为函数并将其添加为扩展?还是那不可能?
    • 对于我可能想要这样做的任何情况,我可能会改用字典。这只是一个有趣的问题。 :)
    • 不用循环初始化,而是使用var array = [String?](count: 6, repeatedValue: nil)来初始化数组。
    【解决方案3】:

    实际上你不能。

    在索引 0 处为空数组的情况下,可以将项目插入到最大索引 index(max) = array.count

    【讨论】:

      【解决方案4】:

      如果您真的希望索引是特定的,而不仅仅是数组中的下一个可用位置,您应该使用带有 Int 键的字典。

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

      【讨论】:

        猜你喜欢
        • 2019-04-09
        • 2023-04-04
        • 1970-01-01
        • 1970-01-01
        • 2010-09-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-21
        相关资源
        最近更新 更多