2015-09-08 67 views
0

我有這個數組用於在swift中存儲'blocks'中的一些小數據。我怎樣才能讀懂Swift中的多維數組?

我曾經有三個字典叫做blockNames,blockTypes和blockImages。但是,我想把所有東西放在一個地方。我想使用如下格式,但我認爲我可以像讀取它一樣; blockData[0.0]["image"]獲得塊0.0的圖像。但是它將數組定義爲雙精度數組,並將它們中的字典定義爲NSObjects。

這是陣列I的談論

let blockData = [ 
    // ===== 0.0 - Air ===== 
    0.0:[ 
     "name":"Air", 
     "image":"0.0.png", 
     "type":"custom" 
    ], 
    0.1:[ 
     "name":"barrier", 
     "image":"barrier", 
     "type":"custom" 
    ], 
    // ===== 1.0 - Dirt ===== 
    1.0:[ 
     "name":"Dirt - Center", 
     "image":"1.0.png", 
     "type":"solid" 
    ], 
    1.1:[ 
     "name":"Dirt width Grass - Center", 
     "image":"1.1.png", 
     "type":"solid" 
    ], 
    1.2:[ 
     "name":"Dirt width Grass - Left", 
     "image":"1.2.png", 
     "type":"solid" 
    ], 
    1.3:[ 
     "name":"Dirt width Grass - Right", 
     "image":"1.3.png", 
     "type":"solid" 
    ], 
    1.4:[ 
     "name":"Dirt - Left", 
     "image":"1.4.png", 
     "type":"solid" 
    ], 
    1.5:[ 
     "name":"Dirt - Right", 
     "image":"1.5.png", 
     "type":"solid" 
    ], 
    1.6:[ 
     "name":"Dirt with Flat Top - Center", 
     "image":"1.6.png", 
     "type":"solid" 
    ], 
    1.7:[ 
     "name":"Dirt with Flat Top - Left", 
     "image":"1.7.png", 
     "type":"solid" 
    ], 
    1.8:[ 
     "name":"Dirt with Flat Top - Right", 
     "image":"1.8.png", 
     "type":"solid" 
    ], 
    1.9:[ 
     "name":"Dirt - Center", 
     "image":"1.9.png", 
     "type":"solid" 
    ], 
    1.11:[ 
     "name":"Dirt - Bottom Center", 
     "image":"1.11.png", 
     "type":"solid" 
    ], 
    ... 
    ] 

我想讀陣列等如下:

let blockID: CGFloat = 0.0 

let blockType = blockData[Float(blockID)]["type"] 

謝謝。

+0

完全正常,它不是一個數組。 –

+0

@ScottHunter我相信OP來自PhP哪裏(有序)的字典被稱爲數組(我知道這很奇怪) – Kametrixom

+0

@Kametrixom在回答你的評論時,我確實來自PHP。但是,你知道一種方法來聲明字典爲String:String而不是NSObject嗎? –

回答

0

這個問題似乎是,你會從你的blockData[0.0]得到一個可選的回報。
您需要使用if let聲明或強制解包來解開該可選項。

let blockData = [ 
    // ===== 0.0 - Air ===== 
    0.0:[ 
     "name":"Air", 
     "image":"0.0.png", 
     "type":"custom" 
    ], 
    0.1:[ 
     "name":"barrier", 
     "image":"barrier", 
     "type":"custom" 
    ], 
    // ===== 1.0 - Dirt ===== 
    1.0:[ 
     "name":"Dirt - Center", 
     "image":"1.0.png", 
     "type":"solid" 
    ], 
    1.1:[ 
     "name":"Dirt width Grass - Center", 
     "image":"1.1.png", 
     "type":"solid" 
    ], 
    1.2:[ 
     "name":"Dirt width Grass - Left", 
     "image":"1.2.png", 
     "type":"solid" 
    ] 
] 

blockData[0.0]!["type"] 

如果元件不被識別的位置工作在迅速2.0

+0

該數組的聲明似乎是[Double:NSObject],所以我無法使用字符串獲取字典。有沒有辦法解決? –

+0

類型強制轉換你的NSObject'if let data = blockData [0.0] as? [String:String]' – milo526

+0

有沒有辦法在第一個decleraton中施放它? –