2015-04-23 31 views
0

我完全被卡住了。我正在Swift中構建一個iOS應用程序。我需要在一個結構中定義一個工具數組,但是如果我包含超過4個項目,Xcode會停滯索引。無法弄清楚如何追加到一個數組(在一個結構內)(Swift)

發現這個問題的解決方案:https://stackoverflow.com/a/27531394。但是,我無法弄清楚如何追加到數組中。當我嘗試執行下面的代碼時,出現以下錯誤:「預期聲明」。有任何想法嗎?

import Foundation 

struct Toolkit { 
    var tools = [ [ 
     "name": "Know Yourself to Lead Yourself", 
     "shape": "icon_knowyourself.pdf", 
     "image": "know_yourself_to_lead_yourself.pdf", 
     "backgroundColor": ["red": 215, "green": 34, "blue": 14, "alpha": 1.0] 
     ], 
     [ 
     "name": "The Core", 
     "shape": "icon_thecore.pdf", 
     "image": "the_core.pdf", 
     "backgroundColor": ["red": 185, "green": 34, "blue": 14, "alpha": 1.0] 
     ], 
     [ 
     "name": "5 Circles of Influence", 
     "shape": "icon_5circles.pdf", 
     "image": "5_circles_of_influence.pdf", 
     "backgroundColor": ["red": 185, "green": 34, "blue": 14, "alpha": 1.0] 
     ], 
     [ 
     "name": "Support Challenge Matrix", 
     "shape": "icon_supportchallenge.pdf", 
     "image": "support_challenge_matrix.pdf", 
     "backgroundColor": ["red": 205, "green": 34, "blue": 14, "alpha": 1.0] 
     ] 
    ] 
    tools.append([ 
     "name": "Creating Healthy Culture", 
     "shape": "icon_healthyculture.pdf", 
     "image": "creating_healthy_culture.pdf", 
     "backgroundColor": ["red": 185, "green": 34, "blue": 14, "alpha": 1.0] 
    ]) 

} 
+1

你不能調用'tools.append()'任何函數或方法外... –

+0

一個明確的類型註釋有時也可以幫助解決「索引無限」問題,在你的情況'var tools:[NSDictionary] = ...' –

回答

0

當您定義結構或類的接口時,您可以執行哪些操作是有限制的。你可以做一些基本的值初始化,但不允許調用像append()這樣的方法。這裏有一個快速的調整到你的代碼,我已經搬到追加到init()方法來代替:

struct Toolkit { 
    var tools = [ [ 
     "name": "Know Yourself to Lead Yourself", 
     "shape": "icon_knowyourself.pdf", 
     "image": "know_yourself_to_lead_yourself.pdf", 
     "backgroundColor": ["red": 215, "green": 34, "blue": 14, "alpha": 1.0] 
     ], 
     [ 
      "name": "The Core", 
      "shape": "icon_thecore.pdf", 
      "image": "the_core.pdf", 
      "backgroundColor": ["red": 185, "green": 34, "blue": 14, "alpha": 1.0] 
     ], 
     [ 
      "name": "5 Circles of Influence", 
      "shape": "icon_5circles.pdf", 
      "image": "5_circles_of_influence.pdf", 
      "backgroundColor": ["red": 185, "green": 34, "blue": 14, "alpha": 1.0] 
     ], 
     [ 
      "name": "Support Challenge Matrix", 
      "shape": "icon_supportchallenge.pdf", 
      "image": "support_challenge_matrix.pdf", 
      "backgroundColor": ["red": 205, "green": 34, "blue": 14, "alpha": 1.0] 
     ] 
    ] 

    init() { 
     tools.append([ 
      "name": "Creating Healthy Culture", 
      "shape": "icon_healthyculture.pdf", 
      "image": "creating_healthy_culture.pdf", 
      "backgroundColor": ["red": 185, "green": 34, "blue": 14, "alpha": 1.0] 
     ]) 
    } 
} 

let kit = Toolkit() 
println(kit.tools) 
相關問題