快速数组总是给我“致命错误:数组索引超出范围". [英] Swift array always give me "fatal error: Array index out of range"

查看:166
本文介绍了快速数组总是给我“致命错误:数组索引超出范围".的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Swift中遇到数组问题,我想制作一个像这样的数组:

I am having a problem with array in Swift, I want to make an array like this :

var Test : [[String]] = [[]]
let test_string = "HELLO"

   for var i = 0; i <= 15; ++i {
      for x in test_string.characters {
         Test[i].append("\(i)\(x)")
      }
   }

print(Test[1][1]) // This should print 1E

但这总是给我这个错误! :

but this always gives me this error ! :

fatal error: Array index out of range

我在这里想念什么?

推荐答案

您的数组数组为空,因此没有Test[0](从技术上讲,您将其初始化为[[]],这意味着它具有一个元素,因此确实存在,但Test[1]则不存在,这很令人困惑.您需要将每个元素初始化为一个空数组:

Your array of arrays is empty, so there is no Test[0] (technically you initialize it to [[]] which means it has one element, so Test[0] does exist, but then Test[1] doesn't, which is confusing). You need to initialize each element to an empty array:

var Test : [[String]] = [] // This really should be an empty array for consistency.
let test_string = "HELLO"

   for var i = 0; i <= 15; ++i {
      Test.append([]) // <== initialize the array
      for x in test_string.characters {
         Test[i].append("\(i)\(x)")
      }
   }

print(Test[1][1]) // This should print 1E

但是,这不是很好的Swift.不建议使用C样式的for循环(同样,变量应始终为驼峰式,不要使用大写字母或使用下划线).

This isn't very good Swift, though. C-style for loops are deprecated (also, variables should always be camelCase, never leading caps or using underscores).

这可以很好地转换为嵌套映射:

This can be translated nicely into a nested mapping:

let testString = "HELLO"
let indexedCharacters = (0..<15).map { i in
    testString.characters.map { c in "\(i)\(c)" }
}

这会根据字符将数字0-15映射到字符串数组中.一旦了解了map的基础知识,这应该比原始循环更容易理解. (我并不是说map通常比for好.通常最好是简单的for-in循环.但是对于这样一个简单的映射,map非常清晰,并且很好地使用了Swift的功能.)

This maps the numbers 0-15 into arrays of strings based on the characters. Once you understand the basics of map, this should be much easier to comprehend than the original loop. (I'm not saying that map is better than for in general. Often a simple for-in loop is best. But for such a simple mapping, map is very clear and uses Swift's features nicely.)

这篇关于快速数组总是给我“致命错误:数组索引超出范围".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆