在Swift 4中,无法为索引类型为'Int'的'Self'类型的值下标吗? [英] Cannot subscript a value of type 'Self' with an index of type 'Int' in Swift 4?

查看:151
本文介绍了在Swift 4中,无法为索引类型为'Int'的'Self'类型的值下标吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

参考链接

这是代码块.

import UIKit
import Foundation
import CoreBluetooth

根据Leo的建议,因此该块中的错误消失了,但索引超出范围仍然存在

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

但是它似乎不起作用. 我在扩展程序集合{}中的return self[index]处收到错误 我也尝试了以下方法,

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?

推荐答案

您应该使用append而不是insert,并且只使用数组下标而不是创建get方法.您只需要在尝试访问索引处的值之前检查数组计数,甚至更好的方法是检查集合索引是否包含索引:

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:

如果您确实要实现get方法,请向索引extension Collection where Index == Int添加约束或将索引参数从Int更改为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"

这篇关于在Swift 4中,无法为索引类型为'Int'的'Self'类型的值下标吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆