ios - 在 swift 4 中修改 [UInt8] 字节数组的最佳方法是什么?

标签 ios arrays swift bluetooth-lowenergy uint8array

您好,我知道你们中的许多人已经知道如何完成,但请帮助我,因为我是 swift 编程的初学者。

请考虑此代码并帮助我进行更改,

//我读的代码

let ReceiveData = rxCharacteristic?.value
        if let ReceiveData = ReceiveData {
            let ReceivedNoOfBytes = ReceiveData.count
            myByteArray = [UInt8](repeating: 0, count: ReceivedNoOfBytes)
            (ReceiveData as NSData).getBytes(&myByteArray, length: ReceivedNoOfBytes)
            print("Data Received ",myByteArray)
               }

//现在我将它们存储到一些局部变量中,如下所示

let b0 = myByteArray[0]
let b0 = myByteArray[1]
let b2 = myByteArray[2]
let b3 = myByteArray[3]

//现在我想插入一些来自文本框的数据

var tb1 = textbox1.text
var b1 = tb1.flatMap{UInt8(String($0))}

var tb2 = textbox2.text
var b2 = tb2.flatMap{UInt8(String($0))}

//现在我正在使用如下的功能 block 写入所有数据

let Transmitdata = NSData(bytes: bytes, length: bytes.count)
                peripheral.writeValue(Transmitdata as Data, for: txCharacteristic!, type: CBCharacteristicWriteType.withoutResponse)
                print("Data Sent",Transmitdata)

我目前正在类声明下创建一个新的字节数组并分配接收到的字节数组。如下图

class Example:UIViwecontroller{

var storebytes: [UInt8]()


func somefunc(){

storebytes = myByteArray

}

然后尝试在 myByteArray 中的前两个位置交换我的文本框数据,然后将其传递给 transmitdata。

有什么简单的方法吗?就像在我需要的地方插入字节然后将它传递给传输?

我试过使用一些方法,比如

bytes.insert(new data,at: index)

但它给了我一个超出范围的索引。有人知道更好的方法吗?

最佳答案

在 Swift 3+ 中,Data 可以用作包含 UInt8 对象的集合类型。

String 中获取一个 Data 对象

let hello = Data("hello".utf8)

你可以简单地将它转换成[UInt8]

let hello1 = [UInt8](hello)

然后回到数据

let hello2 = Data(hello1)

Data 提供所有操作 API,如 appendinsertremove


实际上你不需要[UInt8]。给定两个字符串作为 Data 对象

var hello = Data("Hello !".utf8)
let world = Data("world".utf8)

你可以在hello中插入world

hello.insert(contentsOf: world, at: 6)
print(String(data: hello, encoding: .utf8)!) // "Hello world!"

然后获取一系列数据

let rangeOfWorld = Data(hello[6...11])
print(String(data: rangeOfWorld, encoding: .utf8)!) // "world!"

关于ios - 在 swift 4 中修改 [UInt8] 字节数组的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47883563/

相关文章:

ios - 如何使用 URLSeassion 显示下载进度

ios - https 足以保护登录数据吗?

ios - 导航栏中不同 View Controller 的不同颜色

java - 如何在从另一个类构建的类中搜索单词?

c++ - 模板类型定义的数组初始化

ios - 当 UITextFields 第一响应者改变时, View alpha 和 frame 属性变质

iphone - 将现有对象添加到核心数据?

ios - 如何在 swift 中进行条件转换

c++ - 初始化十二面体数组

Swift:从 appDelegate 更改 tabBar 图标