【问题标题】:Arrays and Swift数组和斯威夫特
【发布时间】:2014-08-01 06:47:26
【问题描述】:

我正在尝试使用 Swift 处理一个应用程序,但使用数组时遇到以下错误:

fatal error: Array index out of range

当应用程序为索引 0 处的数组赋值时会出现这种情况:

class DrawScene: SKScene {

    init(size: CGSize) {
        super.init(size: size)
    }

    var line = SKShapeNode()
    var path = CGPathCreateMutable()
    var touch: UITouch!
    var pts = [CGPoint]()

    override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
        /* Called when a touch begins */
        touch = touches.anyObject() as UITouch!
        self.pts[0] = touch.locationInNode(self)  <-- Error appears here
        drawLine()
    }

一些想法? (我使用的是 xcode 6 Beta 4)

【问题讨论】:

    标签: arrays xcode swift


    【解决方案1】:

    你的数组一开始是空的。

    if self.pts.isEmpty {
        self.pts.append(touch.locationInNode(self))
    }
    else {
        self.pts[0] = touch.locationInNode(self)
    }
    

    【讨论】:

    • 感谢您的解决方案。
    【解决方案2】:

    正如文档中所说:

    “您不能使用下标语法将新项目附加到数组的末尾。如果您尝试使用下标语法来检索或设置超出数组现有边界的索引值,则会触发运行时错误。”

    您必须使用 append+= 添加到空数组。如果您总是想将此点设置为数组中的第一个对象,替换任何已经存在的对象,则必须首先检查数组的计数。

    【讨论】:

      【解决方案3】:

      我不向任何人推荐这个,但是你可以实现你自己的下标来允许你这样做:

      extension Array {
          subscript(safe index: Int) -> Element? {
              get {
                  return self.indices.contains(index) ? self[index] : nil
              }
      
              set(newValue) {
                  guard let newValue = newValue { return }
      
                  if self.count == index {
                      self.append(newValue)                   
                  } else {
                      self[index] = newValue
                  }
              }
          }
      }
      

      您可以按预期使用它:

      var arr = [String]()
      
      arr[safe: 0] = "Test"
      arr[safe: 1] = "Test2"
      print(arr) // ["Test", "Test2"]
      
      arr[safe: 0] = "Test0"
      print(arr) // ["Test0", "Test2"]
      
      arr[safe: 3] = "Test2" // fatal error: Index out of range
      

      【讨论】:

        猜你喜欢
        • 2017-07-22
        • 2017-03-24
        • 2020-07-31
        • 1970-01-01
        • 1970-01-01
        • 2014-09-14
        • 1970-01-01
        • 2016-02-08
        相关资源
        最近更新 更多