Element? { return indices.contain-6ren">
gpt4 book ai didi

ios - 在 swift 4 中使用字节数组时出现 "Fatal error: Index out of range"?

转载 作者:搜寻专家 更新时间:2023-11-01 07:06:13 25 4
gpt4 key购买 nike

我有下面这样的代码,

extension Collection {
func element(at index: Index) -> Element? {
return indices.contains(index) ? self[index] : nil
}
}

class Example: UIViewController{
......

viewDidLoad(){..}
viewDidDisappear(){..}

func readandsend(){
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)
}

//现在我在这里存储我所有的字节数组数据

var first = myByteArray[0]
var sec = myByteArray[1]
var third = myByteArray[2]
var fourth = myByteArray[3]

//我在这里尝试使用上面显示的扩展 block 超出范围

if let b1 = myByteArray.element(at: 0){
one = myByteArray[0]
}
if let b2 = myByteArray.element(at: 1){
two = myByteArray[1]
}
if let b3 = myByteArray.element(at: 2){
three = myByteArray[2]
}
if let b4 = myByteArray.element(at: 3){
four = myByteArray[3]
}

//我有两个文本框,我需要从中获取字符串并转换为 UInt8

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

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

//现在当我尝试发送我完成的字节数组时

 let completedArray = [UInt8]()

completedArray[0] = b1
completedArray[1] = b2
completedArray[2] = myByteArray[2]
completedArray[3] = myByteArray[3]

//写回外设

let TransmitData = NSData(bytes: completedArray, length: completedArray.count)

peripheral.writeValue....so on

当我发送它时出现索引超出范围错误,但我是否正确使用了扩展 block ?有人可以帮忙吗?

最佳答案

您需要使用必要数量的元素初始化数组或追加到数组。

数组初始化:

let completedArray = [UInt8](count: 4)   
completedArray[0] = b1
...

追加:

let completedArray = [UInt8]()
completedArray.append(b1)
...

关于ios - 在 swift 4 中使用字节数组时出现 "Fatal error: Index out of range"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47880934/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com