无法使用 'String!' 类型的索引下标“[Int : [String]]”类型的值

Cannot subscript a value of type '[Int : [String]]' with an index of type 'String!'

请问我,我的错误在哪里?我有 Xcode 错误:

Cannot subscript a value of type '[Int : [String]]' with an index of type 'String!'

in let keyExists = myDict[tmp.Hour] != nil, myDict[tmp.Hour] = Int and myDict[tmp.Hour].append(tmp.Minutes) 的那部分代码:

func array() -> Dictionary <Int,[String]>
    {

        let timeInfos = getTimeForEachBusStop()

        var myDict: Dictionary = [Int:[String]]()


        for tmp in timeInfos {

        let keyExists = myDict[tmp.Hour] != nil
           if (!keyExists) {
                myDict[tmp.Hour] = [Int]()
            }
           myDict[tmp.Hour].append(tmp.Minutes)
            }
        return myDict
    }

我明白了,那个问题是可选类型的,但是我不明白问题在哪里

更新

 func getTimeForEachBusStop() -> NSMutableArray {

        sharedInstance.database!.open()
        let lineId = getIdRoute

        let position = getSelectedBusStop.row + 1


        let getTimeBusStop: FMResultSet! = sharedInstance.database!.executeQuery("SELECT one.hour, one.minute FROM shedule AS one JOIN routetobusstop AS two ON one.busStop_id = (SELECT two.busStop_id WHERE two.line_id = ? AND two.position = ?) AND one.day = 1 AND one.line_id = ? ORDER BY one.position ASC ", withArgumentsInArray: [lineId, position, lineId])


        let getBusStopInfo : NSMutableArray = NSMutableArray()

        while getTimeBusStop.next() {

            let stopInfo: TimeInfo = TimeInfo()
            stopInfo.Hour = getTimeBusStop.stringForColumnIndex(0)
            stopInfo.Minutes = getTimeBusStop.stringForColumnIndex(1)
            getBusStopInfo.addObject(stopInfo)

        }
       sharedInstance.database!.close()
       return getBusStopInfo

    }

错误指出您无法使用 String 键订阅 [Int:[String]] 词典。

因此 tmp.Hour 的类型显然是 String 而不是预期的 Int

如果tmp.Hour保证是整数字符串你可以转换值

let hour = Int(tmp.Hour)!
myDict[hour] = [Int]()

另一方面,由于 myDict[Int:[String]],您可能意味着

let hour = Int(tmp.Hour)!
myDict[hour] = [String]()

小时和分钟的类型为 string(我猜 - stringForColumnIndex)所以您的字典类型错误。应该是:

func array() -> Dictionary <String,[String]>
{

    let timeInfos = getTimeForEachBusStop()

    var myDict: Dictionary = [String:[String]]()


    for tmp in timeInfos {

    let keyExists = myDict[tmp.Hour] != nil
       if (!keyExists) {
            myDict[tmp.Hour] = [String]()
        }
       myDict[tmp.Hour].append(tmp.Minutes)
        }
    return myDict
}

您正在将您的字典声明为具有 Int 类型的键和 [String] 类型的值的字典:

var myDict: Dictionary = [Int:[String]]()

(最好写成:var myDict: [Int: [String]] = [:] 因为通过将其强制转换为 Dictionary 您将删除类型)。

然而,在

myDict[tmp.Hour] = [Int]()

您使用的值是 [Int] 类型,tmp.Hour 可能是 String

所以,您的问题是类型不匹配。