繁体   English   中英

无法为索引类型为“ String!”的“ [Int:[String]]”类型下标!

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

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

无法为索引类型为“ String!”的“ [Int:[String]]”类型下标!

在let keyExists = myDict [tmp.Hour]!= nil中,myDict [tmp.Hour] = Int和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

    }

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

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

(更好地写为: var myDict: [Int: [String]] = [:]因为将其强制转换为Dictionary即可删除类型)。

但是,在

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

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

因此,您的问题是类型不匹配。

该错误表明您无法使用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]()

Hour和Minutes是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
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM