我是Swift的初学者,我正在将应用程序迁移到Swift 3.0
我一直有这个错误,我不知道如何解决它。
"无法调用'价值'使用类型'(字符串)'"
的参数列表它几乎显示在此片段的每一行。 你知道它可能来自哪里吗? 非常感谢
if ((message as AnyObject).value("content") != nil){
stringContent = (message as AnyObject).value("content") as? String
}
if ((message as AnyObject).value("sender_uuid") != nil){
stringSenderUuid = (message as AnyObject).value("sender_uuid") as? String
}
if ((message as AnyObject).value("recipient_uuid") != nil){
stringRecipientUuid = (message as AnyObject).value("recipient_uuid") as! String
}
if ((message as AnyObject).value("date") != nil){
if let result_number = (message as AnyObject).value("date") as? NSNumber
{
stringDate = "\(result_number)"
}
else {
stringDate = (message as AnyObject).value("date") as! String
}
}
此处要求提供有关消息的更多信息
class Messages: Object {
dynamic var channel_name = ""
dynamic var content = ""
dynamic var sender_uuid = ""
dynamic var recipient_uuid = ""
dynamic var date = ""
dynamic var message_uuid = ""
override class func primaryKey() -> String? {
return "message_uuid"
} }
let message = Messages()
message.channel_name=channel_name
message.content=stringContent
message.sender_uuid = stringSenderUuid
message.recipient_uuid = stringRecipientUuid
message.date = stringDate
message.message_uuid = stringUuid
这里有更多信息
// initialize with nothing
var stringContent = " "
var stringSenderUuid = " "
var stringRecipientUuid = " "
var stringDate = " "
var stringUuid = " "
// We check for existence in the dictionnary
if (message["content"] != nil){
stringContent = message["content"] as! String
}
if (message["sender_uuid"] != nil){
stringSenderUuid = message["sender_uuid"] as! String
}
if (message["recipient_uuid"] != nil){
stringRecipientUuid = message["recipient_uuid"] as! String
}
if (message["date"] != nil){
if let result_number = message.value(forKey: "date") as? NSNumber
{
stringDate = "\(result_number)"
}
else {
stringDate = message.value(forKey: "date") as! String
}
}
if (message["uuid"] != nil){
stringUuid = message["uuid"] as! String
}
答案 0 :(得分:5)
您可能需要将其更改为(message as AnyObject).value(forKey:"···")
(添加forKey:
标签)。
你知道对象message
应该是什么类型的对象吗?反复将其转换为AnyObject
是奇怪的。创建新变量let messageObject = message as AnyObject
然后调用messageObject.value(forKey:"···")
会更清晰。 (我怀疑你真的想把它投射到Dictionary
或类似的东西,在这种情况下你可以messageDictionary["···"]
而不是叫value(forKey:)
。)
此外,在Swift中,您可以这样做以进一步减少冗余:
if let content = messageObject.value(forKey:"content") as? String {
stringContent = content
}
答案 1 :(得分:1)
如果message
是json字典,则将其转换为[String:Any]
,然后使用下标。
if let dic = message as? [String:Any] {
stringContent = dic["content"] as? String ?? ""
}
或强>
如果message
的类型为Messages
,那么您可以使用message.content
直接访问其属性,同样也可以访问其他属性。
stringContent = message.content
答案 2 :(得分:0)
如果在测试中遇到此错误(使用LLReactiveMatchers's
sendValues()
使用 eg ),请尝试使您的类型(结构/类)符合{{1} }。