2016-09-24 71 views
3
var myCountry:String? 
var myCity:String? 
var myBodyType:String? 
var myOrientation:String? 
var myRelationship:String? 

我需要從這個數據建立一個字典變量,但是myCountry和myCity我想在一個關鍵字「region」下合併。我試過了:Swift什麼是正確的字典語法?

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

它錯了。這個怎麼做?

回答

12

基本語法是正確的,但是......

...斯威夫特3您收到此錯誤:

heterogenous collection literal could only be inferred to '[String : Any]'; add explicit type annotation if this is intentional

這意味着你必須寫

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

考慮也處理可選項,因爲在Swift中nil的值意味着關鍵缺失