2016-02-28 108 views
0

拜托,问我,我的错误在哪里?我的Xcode错误:不能使用'String!'类型的索引来标记'[Int:[String]]'类型的值

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

,出租keyExists = myDict [tmp.Hour] =零,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 

    } 
+0

你可以发布'getTimeForEachBusStop'的代码吗? – tktsubota

+0

是的,请参阅我的更新 –

回答

0

该错误指出您无法使用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]() 
+0

谢谢,但将来我需要Int类型的字典的键,如何更好地将字符串类型转换为Int? –

+0

我更新了答案。 – vadian

+0

谢谢你,我在你的帮助下发现了我的新错误。现在一切正常!谢谢你,祝你好运! –

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

你可以声明你的字典与[String]类型的Int类型的密钥和值的字典:

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

(更好的写法如下:var myDict: [Int: [String]] = [:]因为它铸造Dictionary你删除类型)。

然而,在

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

您正在使用的值是[Int]型和tmp.Hour可能是一个String

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

相关问题