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

Cannot subscript a value of type 'Self' with an index of type 'Int' in Swift 4?

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

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)

但它 returns 索引超出范围错误。

有人可以 help/advice 解决方案吗?

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