2014-12-26 59 views
1

我一直在寻找这个问题的答案,但不幸的是没有成功。Swift - 使用字典 - 添加多个值

我正在开发一个数学应用程序(基于Swift),它保存用户输入的每个函数的数据。

(我这时就需要使用分析器画上的NSView功能)

数据结构保存Dictionary但我不能增加值和键

Dictionary初始化,如:

var functions = [String : [[String : NSBezierPath], [String : NSColor], [String : CGFloat], [String : Bool]]](); 

//1A.The String key of the main Dictionary is the value of the function, such as "sin(x)" 
//1B.The value of the `Dictionary` is an `Array` od `Dictionaries` 

//2.The first value is a dictionary, whose key is a String and value NSBezierPath() 
//3.The second value is a dictionary, whose key is a String and value NSColor() 
//4.The third value is a dictionary, whose key is a String and value CGFloat() 
//5.The first value is a dictionary, whose key is a String and value Bool() 

要添加的功能,我实现了一个方法(我将报告的一部分):

... 

//Build the sub-dictionaries 

let path : [String:NSBezierPath] = ["path" : thePath]; 
let color : [String:NSColor] = ["color" : theColor]; 
let line : [String:CGFloat] = ["lineWidth" : theLine]; 
let visible : [String:Bool] = ["visible" : theVisibility]; 

//Note that I'm 100% sure that the relative values are compatible with the relative types. 
//Therefore I'm pretty sure there is a syntax error. 


//Add the element (note: theFunction is a string, and I want it to be the key of the `Dictionary`) 

functions[theFunction] = [path, color, line, visible]; //Error here 

... 

我给出的以下错误

'@|value $T10' is not identical to '(String,[([String:NSbezierPath],[String : NSColor],[String : CGFloat],[String : Bool])])' 

我希望这个问题足够清晰和完整。

万一我会立即添加任何您需要的信息。

此致敬意和节日快乐。

回答

1

字典从特定键类型映射到特定值类型。例如,您可以使您的密钥类型String和您的值类型Int

在你的情况下,你已经声明了一个很奇怪的字典:从String(足够公平)到4种不同字典类型的4元组(从字符串到不同类型)的映射。

(这是对我来说是新的,但它看起来是这样的:

var thingy = [String,String]() 

是简写形式,这样的:。

var thingy = [(String,String)]() 

咦奇怪,但它的工作原理你的字典是使用变种这个窍门)

这意味着你需要创建一个4元组的数组(请注意附加括号):

functions[theFunction] = [(path, color, line, visible)] 

我猜你不是故意这样做。你真的想要一个这4种不同字典类型的数组吗?如果是这样,那么你运气不好 - 你不能在同一个数组中存储不同类型的字典(它们的值有不同类型的字典)。

(嗯,你可以,如果你做的字典Any的价值观 - 但这是一个可怕的想法,将是一场噩梦使用)

也许你想要的结果是这样的(即进行从functions字典地图一个字符串,不同类型的词典)的4元组:

var functions = [String : ([String : NSBezierPath], [String : NSColor], [String : CGFloat], [String : Bool])]() 

你会赋值到字典中类似这样的(注意,没有方括号在RHS):

functions[theFunction] = (path, color, line, visible) 

这会起作用,但与它合作会很不愉快。但是,你是否真的想将结构化数据存储在字典和数组中?这不是JavaScript ;-)你会把自己绑在导航多级字典的节点上。声明一个结构!在你的代码中使用它会容易得多。

struct Functions { 
    var beziers: [String:NSBezierPath] 
    var color: [String:NSColor] 
    var line: [String:NSColor] 
    var floats: [String:CGFloat] 
    var bools: [String:Bool] 
} 
var functions: [String:Functions] = [:] 

更妙的是,如果所有的贝济耶,颜色等应该是使用相同的密钥引用,声明包含了所有这些或类似的字典。

+0

谢谢你的回答。 它帮了我很多! 我终于决定按照你的建议来声明一个结构体,它的功能就像一个魅力!再次感谢你! –