swift byte数组添加元素时报错 索引超出范围

xiaote 发布于 2016/02/04 11:10
阅读 399
收藏 0

代码如下

func packData(type:Int,content:[Int],length:Int) -> [UInt8] {

        var i:Int = 0
        var pack:[UInt8] = []
        pack[0] = (UInt8)(0xff&0xef)
        pack[1] = 0x01
        pack[2] = (UInt8)(0xff&type)
        pack[3] = (UInt8)(0xff&((length+2)/256))
        pack[4] = (UInt8)(0xff&((length+2)%256))
        var crc:Int = type.hashValue + pack[3].hashValue + pack[4].hashValue
        for  i = 0; i < length; i++ {
            pack[i+5] = (UInt8)(0xff&content[i])
            crc += content[i]
        }
        pack[i+5] = (UInt8)(0xff&(crc/256))
        pack[i+6] = (UInt8)(0xff&(crc%256))

        return pack

    }

调用

let byte:[UInt8] = packData(1, content: [0,0,1,1,2,3,4,5,6,7,8,9,10], length: 10)
        print(byte)

报错

在 pack[0] = (UInt8)(0xff&0xef) 这里报错 array index out of range
应该怎么修改代码

加载中
返回顶部
顶部