【问题标题】:What is the best way to modify a [UInt8] byte array in swift 4?在 swift 4 中修改 [UInt8] 字节数组的最佳方法是什么?
【发布时间】:2018-06-01 16:29:39
【问题描述】:

嗨,我知道你们中的许多人已经知道如何做到这一点,但请帮助我,因为我是 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))}

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

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 中前两个位置的位置,然后将其传递给传输数据。

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

我尝试过使用类似的方法

bytes.insert(new data,at: index)

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

【问题讨论】:

    标签: ios arrays swift bluetooth-lowenergy uint8array


    【解决方案1】:

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

    拥有来自StringData 对象

    let hello = Data("hello".utf8)
    

    您可以简单地将其转换为[UInt8]

    let hello1 = [UInt8](hello)
    

    然后返回Data

    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!"
    

    【讨论】:

    • 嗨 vadian,感谢您的回复。我有点困惑,你能在我的代码中展示如何执行集合类型吗? :)
    • tb1.flatMap{UInt8(String($0) 应该做什么?
    • 嗨,谢谢,现在我明白了 :) 好吧 textbox.text 返回一个字符串,即“12”,但我必须将其转换为两个 UInt8 数字,所以当我使用上面的平面图时,我得到 [ 1,2] 和它的 UInt8。希望有帮助
    • 我明白了。我用字母试了一下,当然没用。
    • 是的,我认为它不适用于字母,这就是为什么我将文本框文本键盘放在数字上:)
    猜你喜欢
    • 2011-01-04
    • 1970-01-01
    • 1970-01-01
    • 2018-03-15
    • 2019-04-23
    • 1970-01-01
    • 1970-01-01
    • 2017-10-23
    • 1970-01-01
    相关资源
    最近更新 更多