This post is somwhat related to a prior poston the old forums.
I have two dictionaries, and I want to verify that a few values in each are of the proper class, and after that then compare their values.
This compiles but fails:
var looksTheSame = true
let keys: [String: AnyClass] = ["modify_time": NSDate.self, "schedule_time": NSDate.self, "status": NSString.self] // String.self?
for (key, value) in keys {
print("OLD: \(key) old=\(oldInfo[key]) new=\(info[key])")
guard
let old = oldInfo[key] where old.dynamicType === value,
let new = info[key] where ney.dynamicType === value
else { looksTheSame = false; break }
... now I can compare objects
}
print(looksTheSame) // FAILS
I tried a number of other attems to essentially grab some property of the class, then use that to compare it against the instance dynamicType, no no avail.
What I did find that works is to create a "key" dictionary with a random instance of the proper object (ie NSDate() or ""), and then compare object type to object type:
var looksTheSame = true
let keys: [String: AnyObject] = ["modify_time": NSDate(), "schedule_time": NSDate(), "status": ""]
for (key, value) in keys {
guard
let old = x[key] where old.dynamicType === value.dynamicType,
let new = x[key] where new.dynamicType === value.dynamicType
else { looksTheSame = false; break }
... now I can compare objects
}
print(looksTheSame) // SUCCESS
Is there a better way to do this?
With this code, I get the following:
let keys: [String: AnyClass] = ["modify_time": NSDate.self, "schedule_time": NSDate.self, "status": NSString.self]
for (key, value) in keys {
print("OLD: \(key) old=\(oldInfo[key]) new=\(info[key])")
print(value)
//`guard` gets meaningless, just for experiment...
print(oldInfo[key]!.dynamicType)
print(info[key]!.dynamicType)
guard
let old = oldInfo[key] where old.dynamicType === value,
let new = info[key] where new.dynamicType === value
else { looksTheSame = false; break }
//...
}
Output:
NSDate
__NSDate
__NSDate
It seems NSDate is implemented as sort of class cluster, and the actual type of your NSDate instance is not NSDate itself.
In fact, while I was editing the Playground file, the output changed like this:
NSDate
__NSDate
__NSTaggedDate
Which means, your latter code may fail if any of the NSDate instances have other types than the referece instance NSDate().
Maybe you need to use Objective-C runtime feature, if such runtime type checking is required.
let keys: [String: AnyClass] = ["modify_time": NSDate.self, "schedule_time": NSDate.self, "status": NSString.self]
for (key, value) in keys {
print("OLD: \(key) old=\(oldInfo[key]) new=\(info[key])")
guard
let old = oldInfo[key] where (old as! NSObject).isKindOfClass(value),
let new = info[key] where (new as! NSObject).isKindOfClass(value)
else { looksTheSame = false; break }
//...
}
print(looksTheSame)