2016-02-28 109 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

所以,你的問題是類型不匹配。

相關問題