我一直在获得一个超出范围错误的数组索引,然后遇到了这个问题。
这是代码块。
import UIKit
import Foundation
import CoreBluetooth
编辑1:从Leo建议的,所以错误从这个区块消失,但索引超出范围仍然存在
extension Collection where Index == Int {
func get(index: Int) -> Element? {
if 0 <= index && index < count {
return self[index]
} else {
return nil
}
}
}
class Sample:UIViewController{
.......
//This is where I'm sending data
func send(){
if let send1 = mybytes.get(index: 2){
byteat2 = bytefromtextbox
print(byteat2)
}
}
}
但它似乎没有用。我在return self[index]
的扩展集{}中收到错误我也试过以下内容,
byteat2.insert(bytefromtextbox!, at:2)
但它返回索引超出范围错误。
有人可以帮助/建议解决方案吗?
你应该使用append
而不是insert
,只使用数组下标而不是创建一个get方法。您只需要在尝试访问索引处的值之前检查数组计数,否则更好的方法是检查集合索引是否包含索引:
如果你真的想要实现一个get方法,请在索引extension Collection where Index == Int
中添加一个约束,或者将你的索引参数从Int
更改为Index
:
extension Collection {
func element(at index: Index) -> Element? {
return indices.contains(index) ? self[index] : nil
}
}
let array = ["a","b","c","d"]
array.element(at: 2) // "c"