比较 Swift 中的 AnyObject [英] Comparing AnyObject in Swift
问题描述
我无法将此 Objective-C 代码移植到 Swift.代码必须按照给定的 property
对目录的内容进行排序.
I'm having trouble porting this Objective-C code to Swift. The code must sort the contents of a directory by a given property
.
NSArray *contents = [fileManager contentsOfDirectoryAtURL:directoryURL includingPropertiesForKeys:@[property] options:kNilOptions error:&error];
if (!contents) return nil;
contents = [contents sortedArrayUsingComparator:^NSComparisonResult(NSURL *url1, NSURL *url2) {
id value1;
if ([url1 getResourceValue:&value1 forKey:property error:nil]) return NSOrderedAscending;
id value2;
if ([url2 getResourceValue:&value2 forKey:property error:nil]) return NSOrderedDescending;
return [value1 compare:value2];
}];
return contents
到目前为止我的 Swift 版本:
My Swift version so far:
if let contents = fileManager.contentsOfDirectoryAtURL(directoryURL, includingPropertiesForKeys: [property], options: NSDirectoryEnumerationOptions.allZeros, error: &error) as? [NSURL] {
let sortedContents = contents.sorted({(URL1 : NSURL, URL2 : NSURL) -> Bool in
var value1 : AnyObject?
if !URL1.getResourceValue(&value1, forKey: property, error: nil) { return true }
var value2 : AnyObject?
if !URL2.getResourceValue(&value2, forKey: property, error: nil) { return false }
// How do I compare AnyObject?
return false
})
return sortedContents
} else {
return nil
}
特别是,我不知道如何比较两个 AnyObject
对象.我不能向下转换到 Comparable
协议,因为它没有被标记为 @objc
并且显然我不能用可选的链接语法调用 compare
(错误:后缀?"的操作数应该有可选类型;类型是NSComparisonResult").
Particularly, I don't know how to compare two AnyObject
objects. I can't downcast to the Comparable
protocol because it's not marked as @objc
and apparently I can't call compare
with optional chaining syntax (error: Operand of postfix '?' should have optional type; type is 'NSComparisonResult').
当然,总是有将值向下转换为 String、NSDate 和 NSNumber 的蛮力方法:
Of course, there's always the brute-force approach of downcasting the values to String, NSDate and NSNumber:
if let string1 = value1 as? String {
if let string2 = value2 as? String {
return string1 < string2
}
}
if let date1 = value1 as? NSDate {
if let date2 = value2 as? NSDate {
return date1.compare(date2) == NSComparisonResult.OrderedAscending
}
}
// And so on...
return false
有没有更好的方法?
推荐答案
除非它们确实是 AnyObject
(即,它们可以是快速的事物)将它们声明(或强制转换)为 NSObject
代替.
Unless they really are AnyObject
(ie., they can be swift things) declare them (or cast them) to NSObject
instead.
这篇关于比较 Swift 中的 AnyObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!