我想知道是否可以在swift中的索引1处插入元素,但不插入索引0,如下所示:
var array = [String]()
array.insert("cow", atIndex: 1)
但每次尝试时,我都会收到旧的致命错误:数组索引超出范围错误消息。
这个问题到底有没有?如有任何建议,我们将不胜感激!谢谢
如果将其设为一个可选数组,并首先初始化所需的元素数量,则可以接近。
var array = [String?]()
for i in 0...5 {
array.append(nil)
}
array.insert("cow", atIndex: 1)
如果您真的希望索引是特定的,而不仅仅是数组中的下一个可用位置,那么应该使用带有Int键的字典。
var dict = [Int:String]()
dict[1] = "Cow"
dict[5] = "Chicken"
您可以创建一个自定义列表。你需要添加一些检查,以确保项目不是空的或超出索引,等等。
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;
}
}
}
实际上你做不到。
在索引0处为空数组的情况下,项可以插入到最大索引index(max) = array.count
。