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

五迷三道 提交于 2019-12-13 02:59:21

问题


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:


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"


来源:https://stackoverflow.com/questions/47877893/cannot-subscript-a-value-of-type-self-with-an-index-of-type-int-in-swift-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!