I've been recently trying to figure out how to init a Dictionary in swift like i used to do in Objective-c:
我最近一直在试图弄清楚如何像在Objective-c中那样快速地init一个字典:
NSMutableDictionary *loginDictionary = [[NSMutableDictionary alloc] initWithObjects:@[UsernameTextfield.text,PasswordTextfield.text] forKeys:@[@"username",@"password"];
i tried to write it in Swift :
我试着用Swift写:
let userDictionary = NSMutableDictionary.init(object: [usernameTextField.text,passwordTextField.text], forKey: ["username","password"])
But i get an error:
但我犯了一个错误:
Contextual type AnyObject cannot be used with array literal.
上下文类型AnyObject不能与数组文本一起使用。
2 个解决方案
#1
6
First of all, you have to use the same method, with objects
and forKeys
(note the plural).
首先,你必须使用相同的方法,对象和forKeys(注意复数)。
Then you need to tell the compiler what type is each object, in your case it's strings from Optional text labels, so you could do something like this:
然后你需要告诉编译器每个对象是什么类型,在你的例子中,它是来自可选文本标签的字符串,所以你可以这样做:
if let name = usernameTextField.text as? String, let pass = passwordTextField.text as? String {
let userDictionary = NSMutableDictionary(objects: [name, pass], forKeys: ["username", "password"])
}
#2
0
You are Passing Objects
and Keys
in NSMutableDictionary
as below, replace your code as below.
在NSMutableDictionary中传递对象和键,如下所示,替换代码。
let userDictionary = NSMutableDictionary(objects: [usernameTextField.text,passwordTextField.text], forKeys: ["username","password"])
#1
6
First of all, you have to use the same method, with objects
and forKeys
(note the plural).
首先,你必须使用相同的方法,对象和forKeys(注意复数)。
Then you need to tell the compiler what type is each object, in your case it's strings from Optional text labels, so you could do something like this:
然后你需要告诉编译器每个对象是什么类型,在你的例子中,它是来自可选文本标签的字符串,所以你可以这样做:
if let name = usernameTextField.text as? String, let pass = passwordTextField.text as? String {
let userDictionary = NSMutableDictionary(objects: [name, pass], forKeys: ["username", "password"])
}
#2
0
You are Passing Objects
and Keys
in NSMutableDictionary
as below, replace your code as below.
在NSMutableDictionary中传递对象和键,如下所示,替换代码。
let userDictionary = NSMutableDictionary(objects: [usernameTextField.text,passwordTextField.text], forKeys: ["username","password"])