数组和Swift [英] Arrays and Swift

查看:73
本文介绍了数组和Swift的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to deal with an app in Swift and I'm facing the following error using arrays:

fatal error: Array index out of range

当应用程序为索引0的数组分配值时出现:

This appears when apps assign a value to the array at index 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)

Some ideas? (I'm using xcode 6 Beta 4)

推荐答案

您的数组最初是空的.

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

这篇关于数组和Swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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