斯威夫特词典 [英] Dictionary in Swift
问题描述
var myDic3 = [String:AnyObject]()
和
var myDic2 = Dictionary< Int,AnyObject>()
和
var myDic4 = [:]
当我声明像myDic4时,我无法添加键值和值:
myDic4 [001] =ABC
错误是无法分配给此表达式的结果
您可以通过四种不同的方式声明并初始化Swift中的一个空字典:
-
var myDic1 = [String:AnyObject]()
-
var myDic2 = Dictionary< String:AnyObject>()
-
var myDic3:[String:AnyObject] = [:]
-
var myDic4:Dictionary< String:AnyObject& GT; = [:]
这些都会给你相同的结果,这是一个具有 String
作为键, AnyObject
作为值。
[String:AnyObject]
只是 Dictionary< String,AnyObject>
的缩写。他们的意思是同样的事情。
在上述情况1和2中,变量的类型由Swift从分配给它们的值推断出来。在上述情况3和4中,类型被明确地分配给变量,然后用空字典初始化 [:]
。
当您创建这样的字典时:
var myDic5 = [:]
Swift没有什么可做的,它推断你的字典是类型 NSDictionary
。问题是 NSDictionary
是一个不可变类型(你不能改变它)。可变等价物是一个 NSMutableDictionary
,所以这将工作:
var myDic6:NSMutableDictionary = [:]
但是,您应该更喜欢使用上面的案例1或3,因为 NSMutableDictionary
不是Swift类型,而是来自Foundation框架。事实上,你甚至可以做 var myDic = [:]
的唯一原因是因为你已经导入了基础框架(使用 import UIKit
, import Cocoa
或 import Foundation
)。没有导入基础,这是一个语法错误。
I really confuse with the way we create dictionary in swift. So could you please tell me what is the different between
var myDic3 = [String : AnyObject]()
and
var myDic2 = Dictionary <Int,AnyObject>()
and
var myDic4 = [ : ]
When i declare like myDic4 I cannot add key and value for it:
myDic4["001"] = "ABC"
And the error is "Cannot assign to the result of this expression"
You can declare and initialize an empty Dictionary in Swift in 4 different ways:
var myDic1 = [String : AnyObject]()
var myDic2 = Dictionary<String: AnyObject>()
var myDic3: [String: AnyObject] = [:]
var myDic4: Dictionary<String: AnyObject> = [:]
These will all give you the same result which is a Dictionary with String
s as the keys and AnyObject
s as the values.
[String: AnyObject]
is just shorthand for Dictionary<String, AnyObject>
. They mean the same thing.
In cases 1 and 2 above, the types of the variables are inferred by Swift from the values being assigned to them. In cases 3 and 4 above, the types are explicitly assigned to the variables, and then they are initialized with an empty dictionary [:]
.
When you create a dictionary like this:
var myDic5 = [:]
Swift has nothing to go on, and it infers your dictionary to be of type NSDictionary
. The problem is that NSDictionary
is an immutable type (you can't change it). The mutable equivalent is an NSMutableDictionary
, so this would work:
var myDic6: NSMutableDictionary = [:]
but you should prefer using cases 1 or 3 above since NSMutableDictionary
isn't a Swift type but instead comes from the Foundation framework. In fact, the only reason you can even do var myDic = [:]
is because you have imported the Foundation framework (with import UIKit
, import Cocoa
, or import Foundation
). Without importing Foundation, this is a syntax error.
这篇关于斯威夫特词典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!