![](/img/trans.png)
[英]Cannot subscript a value of type '[String : Int]' with an index of type '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.