解决!请参阅本文底部的解决方案
我尝试使用Alamofire创建一个JSON对象用于我的后端。我能够添加一个带有String值的键,但似乎无法将Array的值添加到AnyObject。我虽然会非常直接,但我还没能找到解决方案。
func someFunction(btn: UIButton){
var someDictionary = Dictionary<String, AnyObject>()
let someArray = [textField[1].text,textField[2].text,textField[3].text]
someDictionary["answer"] = textField[0].text
someDictionary["options"] = someArray as? Array // <---- Can't be assigned to AnyObject
let url = "http://localhost:3000/api/question"
Alamofire.request(.POST, url, parameters: someDictionary).responseJSON { response in
if let JSON = response.result.value as? Dictionary<String, AnyObject>{
}
}
}
解决方案:删除as? Array
并创建循环以附加已初始化的数组
func someFunction(btn: UIButton){
var someDictionary = Dictionary<String, AnyObject>()
var SomeArray = [String]()
for i in 1...3{ //created loop to append the textField text
SomeArray.append(textField[i].text!)
}
someDictionary["answer"] = textField[0].text
someDictionary["options"] = SomeArray // Removed "as? Array"
let url = "http://localhost:3000/api/question"
Alamofire.request(.POST, url, parameters: someDictionary).responseJSON { response in
if let JSON = response.result.value as? Dictionary<String, AnyObject>{
print("JSON Response From Server-->\(JSON)")
}
}
}
答案 0 :(得分:2)
清理项目并再次运行。您的代码对我有用,我可以分配
func someFunction(btn: UIButton){
var someDictionary = Dictionary<String, AnyObject>()
let someArray = ["SomeString","SomeString","SomeString"]
someDictionary["answer"] = textFields[0].text
someDictionary["options"] = someArray // now you can assign
let url = "http://localhost:3000/api/question"
Alamofire.request(.POST, url, parameters: someDictionary).responseJSON { response in
if let JSON = response.result.value as? Dictionary<String, AnyObject>{
}
}
}