不能下标类型' [Int:[String]]'索引类型为' String!'

时间:2016-02-28 17:15:30

标签: ios swift optional

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

  

无法下标类型' [Int:[String]]'索引为   键入' String!'

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

我明白,这个问题属于可选类型,但问题在哪里我不明白

UPD

 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

    }

3 个答案:

答案 0 :(得分:1)

您将字典声明为字典,其键为Int,类型为[String]

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

(更好地写为:var myDict: [Int: [String]] = [:],因为通过将其转换为Dictionary,您将删除类型。)

然而,在

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

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

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

答案 1 :(得分:0)

该错误表明您无法使用[Int:[String]]密钥订阅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]()

答案 2 :(得分:0)

小时和分钟的类型为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
}