不能下标类型' Self'索引类型' Int'在Swift 4中?

时间:2017-12-18 23:23:09

标签: ios arrays swift indexoutofrangeexception

我的数组索引超出了范围错误,然后遇到了这个问题。

Reference link

这是代码块。

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)

但它返回一个超出范围错误的索引。

有人可以帮助/建议解决方案吗?

1 个答案:

答案 0 :(得分:0)

您应该使用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"