[英]Swift generics doesn't work as expected with JSON dictionary came from Objective-C parser
I have a function to retrieve non optional value from JSON dictionary. 我有一个从JSON字典中检索非可选值的函数。 It takes 3 params: dictionary, key and default value for a case where is no value in a dictionary or value have wrong type
它需要3个参数:字典,键和默认值(如果字典中没有值或值的类型错误)
func valueFromJSONDict<T>(dict:[NSObject: AnyObject]?, key: NSObject, defaultValue: T) -> T {
if let value = dict?[key] as? T {
return value
}
return defaultValue
}
The problem is it always returns the default value. 问题在于它总是返回默认值。
title = valueFromJSONDict(dict, "title", "")
but if I do same thing without generics it works fine: 但是,如果我在没有泛型的情况下也做同样的事情,那么效果很好:
title = { () -> String
if let value = dict?["title"] as? String {
title = value
} else {
return ""
}
}()
This parsed JSON dict is coming from Objective-C parser and if I println
dynamicType
of value from the dict is like __CFNSString
, but T.self
is Swift.String
, so Swift is unable to figure out types probably 这解析JSON字典从Objective-C的语法分析器来了,如果我
println
dynamicType
的值从字典就像__CFNSString
,但T.self
是Swift.String
,所以斯威夫特无法大概判断出类型
How do I make it work? 我该如何运作?
What does your dict
object look like? 您的
dict
对象是什么样的?
Here is what I would suggest: 这是我的建议:
typealias JSONObject = [String: AnyObject]
func valueFromJSON<T>(json: JSONObject?, key: String, defaultValue: T) -> T
{
if let value = json?[key] as? T {
return value
}
return defaultValue
}
let json = ["Name": "Sir Lancelot",
"Quest": "To seek the Holy Grail",
"Favorite Color": "Blue..."]
let name = valueFromJSON(json, "Name", "Sir Not Appearing In This Film")
I discovered, that method actually work is I assign the result to some var or let : 我发现,该方法实际上是在将结果分配给某些var或let :
let value = valueFromJSONDict(dict, "title", "") // value from JSON
but didn't work if I assign the result to a property : 但如果我将结果分配给属性,则不起作用 :
title = valueFromJSONDict(dict, "title", "") // always ""
So finally I've fixed this issue by replacing my property type from non-optional @NSManaged var title: String
to implicitly unwrapped optional @NSManaged var title: String!
因此,最后我通过将属性类型从非可选
@NSManaged var title: String
替换 为隐式展开的可选 @NSManaged var title: String!
来 解决了此问题 @NSManaged var title: String!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.