簡體   English   中英

在Swift 4中,無法為索引類型為'Int'的'Self'類型的值下標嗎?

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

我一直在獲取數組索引超出范圍錯誤,然后遇到了這個問題。

參考鏈接

這是代碼塊。

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

但這似乎不起作用。 我在擴展Collection {}的return self[index]中遇到錯誤,我也嘗試了以下方法,

byteat2.insert(bytefromtextbox!, at:2)

但是它返回索引超出范圍錯誤。

有人可以幫助/建議解決方案嗎?

您應該使用append而不是insert而只使用數組下標而不是創建get方法。 您只需要在嘗試訪問索引處的值之前檢查數組計數,甚至更好的方法是檢查集合索引是否包含索引:

如果您確實要實現get方法,請向索引extension Collection where Index == Int添加一個約束, 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"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM