用nsmutabledata swift

时间:2016-01-28 18:15:03

标签: ios arrays swift byte bytearray

如何在swift中使用nsmutabledata填充数组?

继承我的代码:

    func hashTest(hash:[UInt8]) {
        var arrayOfBytes = NSMutableData()
        for var i = 0; i < hash.count; i++ {
            if i < 21 {
                arrayOfBytes.appendBytes(hash[i] as UInt8, length: 1)
            }
        }
    }

但我收到以下错误:

Cannot invoke initializer for type 'UnsafePointer<UInt8>' with an argument list of type '(UInt8)'

我试图重复这样的事情:

let endMarker = NSData(bytes: [0xa1, 0x11, 0xa9, 0xf5, 0xce, 0xdb, 0x18, 0xfb, 0xed, 0xd7, 0x67, 0x25, 0x86, 0xe7, 0xd6, 0x42, 0x96, 0x0f, 0x95, 0xe8] as [UInt8], length: 20)

1 个答案:

答案 0 :(得分:1)

只需将&放在hash[i]前面,这将允许不安全的指针进入附加字节

func hashTest(var hash:[UInt8]) {
        var arrayOfBytes = NSMutableData()
        for var i = 0; i < hash.count; i++ {
        if i < 21 {
            arrayOfBytes.appendBytes(&hash[i], length: 1)
        }
    }
}