简体   繁体   English

字典数组中的Swift字典

[英]Swift Dictionaries in Arrays in Dictionary

I'm trying to understand why dico["tickets"] is not of the [Any] type : 我试图了解为什么dico [“ tickets”]不是[Any]类型的:

import Foundation

var array: [Any]!

let dico: [String: Any] = ["tickets": [["itemLines": [["name": "kebab", "units": 1], ["name": "muffin", "units": 1], ["name": "coca-cola", "units": 2]]]], "totale": 225.00]


if let tickets = dico["tickets"] as? [Any] {
    array = tickets
}

println(array)

(Xcode 6 GM) (Xcode 6 GM)

Any clue ? 有什么线索吗?

Don't use Any unless you absolutely have to. 除非绝对必要,否则不要使用Any Reasoning about it, in exactly this kind of situation, is very tricky. 在这种情况下,对此进行推理非常棘手。 Swift has type-parameterization (generics) for a reason. Swift具有类型参数化(泛型)是有原因的。 In most cases you want a struct anyway. 在大多数情况下,无论如何您都想要一个结构。

I tried to write out what the type of this thing would actually be, but it's not really possible to write in Swift. 我试图写出这种东西的实际类型,但是用Swift编写实际上是不可能的。 The second element is [String:Float] , which is fine. 第二个元素是[String:Float] ,这很好。 But the first element is [String:[[String: Any]]] , which is a type that Swift will not implicitly promote to (and also happens to be a really insane type). 但是第一个元素是[String:[[String: Any]]] ,这是Swift不会隐式提升为的类型(并且恰好是一个非常疯狂的类型)。 Swift only promotes to Any if you explicitly ask for it exactly where you want it to do so. 如果您明确要求将Swift确切地升至Any则Swift只会升为Any That's why it doesn't quietly promote to [Any] here. 这就是为什么它不会在这里悄悄提升为[Any] That's a feature. 这是一个功能。 If it were otherwise, all kinds of things would quietly promote to Any and the compiler errors would be even more confusing. 如果不是这样,那么各种各样的事情都会悄悄地升级为Any ,并且编译器错误将更加令人困惑。

The answer is to avoid Any . 答案是避免Any What you really have here are a couple of structs: 您真正拥有的是以下两个结构:

struct Item {
  let name: String
  let units: Int
}

struct Dico {
  let tickets: [Item]
  let totale: Float
}

let dico = Dico(tickets: [
  Item(name: "kebab", units: 1),
  Item(name: "muffin", units: 1),
  Item(name: "coca-cola", units: 2)
  ],
  totale: 225.00 )

let tickets = dico.tickets

This is how you should store and deal with your data. 这就是应该存储和处理数据的方式。 If you're starting with something like JSON that returns you a bunch of Any objects, you should parse it into data structures before using it. 如果您以类似JSON的形式返回了很多Any对象,则应在使用它之前将其解析为数据结构。 Otherwise you will fight with this insane dictionary all over the code. 否则,您将在整个代码中使用这个疯狂的字典。 I've been writing about JSON parsing in Swift in a series that started with Functional Wish Fulfillment . 我一直在写Swift的JSON解析文章,该文章以Functional Wish Fulfillment开始。 I link there to several other similar approaches. 我在那里链接到其他几种类似的方法。 The same basic technique applies to any parser, not just JSON. 相同的基本技术适用于所有解析器,而不仅仅是JSON。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM