简体   繁体   English

Swift什么是字典的正确语法?

[英]Swift what is correct syntax of dictionary?

 var myCountry:String?
var myCity:String?
var myBodyType:String?
var myOrientation:String?
var myRelationship:String?

I need to build a dictionary variable from this data but the myCountry and myCity I want to combine under the one key "region". 我需要从这个数据构建一个字典变量,但myCountry和myCity我想在一个键“region”下组合。 I tryed: 我试过:

var myData = ["region":["country":myCountry,"city":myCity],"bodyType":myBodyType,"orientation":myOrientation,"relationship":myRelationship]

its wrong. 这是不对的。 how to do this? 这个怎么做?

Basically the syntax is correct, but ... 基本上语法是正确的,但是......

...in Swift 3 you get this error: ...在Swift 3中你得到这个错误:

heterogenous collection literal could only be inferred to '[String : Any]'; 异构集合文字只能推断为'[String:Any]'; add explicit type annotation if this is intentional 如果这是故意的,请添加显式类型注释

That means you have to write 这意味着你必须写

var myData : [String:Any] = ["region" ...

Consider also to handle the optionals because in Swift a nil value means the key is missing . 还要考虑处理选项,因为在Swift中, nil值表示缺少键

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

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