我正在尝试在 swift 中实现一个存储字符串数组的字典数据结构。我已经这样声明了:
var journeyDetails = [Int: [String]]()
当我想向其附加实际字符串时,我会这样做
if let journeys = fetchedData["journeys"] as? [[String: Any]]{
var nr_of_journey : Int = 0
for journey in journeys{
self.journeyDetails[nr_of_journey]?.append("The starting date and time of the journey are: "+String(describing: journey["startDateTime"]))
}
}
nr_of_journey = nr_of_journey + 1
等等。但是,journeyDetails
不断返回nil
。我应该做任何其他类型的初始化吗?为什么没有附加数据?
最佳答案
最初,journeyDetails
中没有键或值,因此每次使用 self.journeyDetails[nr_of_journey]
都会返回 nil
。
如果您使用的是 Swift 4,则可以指定在给定键当前没有值的情况下要使用的默认值。
更新行:
self.journeyDetails[nr_of_journey]?.append("The starting date and time of the journey are: "+String(describing: journey["startDateTime"]))
至:
self.journeyDetails[nr_of_journey, default: []].append("The starting date and time of the journey are: "+String(describing: journey["startDateTime"]))
如果给定的 nr_of_journey
键当前没有值,这会提供一个默认的空数组。
关于swift - Swift 中的字典数据结构返回 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49211301/