Cannot subscript a value of type 'Self' wi

2019-08-18 03:50发布

I have been getting an array index out of range error and then came across this question.

Reference link

And this is the block of code.

import UIKit
import Foundation
import CoreBluetooth

EDIT 1: From what Leo suggested, so the error is gone from this block but index out of range still persists

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)
        }
    }
}

But it doesn't seem to work. I get an error at return self[index] in extension Collection{} I have also tried the following,

byteat2.insert(bytefromtextbox!, at:2)

But it returns an index out of range error.

Can someone help/advice a solution?

1条回答
贼婆χ
2楼-- · 2019-08-18 04:40

You should use append instead of insert and just use array subscript instead of creating a get method. You just need check the array count before trying to access the value at the index or even better approach would be checking if the collection indices contains the index:

If you really want to implement a get method add a constraint to the index extension Collection where Index == Int or change your index parameter from Int to 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"
查看更多
登录 后发表回答