0

将我的代码转换为 swift 3 后,出现错误:

noteObjects.sort (comparator: { (first : AnyObject, second : AnyObject) -> ComparisonResult in

            if  let f : String = (first as! RChannels).name!   {
            let s : String = (second as! RChannels).name!

                return f.compare(s)
            }

        } as! (Any, Any) -> ComparisonResult)  // error here

这一行as! (Any, Any) -> ComparisonResult)给了我一个错误,上面写着(lldb),没有任何其他描述,任何人都可以解释这里出了什么问题?在转换之前是这样的:

noteObjects.sortUsingComparator { (first : AnyObject, second : AnyObject) -> NSComparisonResult in
        if  let f : String = (first as! RChannels).name!   {
            let s : String = (second as! RChannels).name!
            return f.compare(s)
        }
     }

noteObjects是一个 NSMutableArray

4

1 回答 1

0

摆脱as! (Any, Any) -> ComparisonResult并将这两个参数更改为Any而不是AnyObject

noteObjects.sort(comparator: { (first : Any, second : Any) -> ComparisonResult in
    if let f : String = (first as! RChannels).name! {
        let s : String = (second as! RChannels).name!

        return f.compare(s)
    }
})

但这仍然存在一些问题。您没有return每个代码路径的值,并且您没有正确处理选项。以下会更好:

noteObjects.sort(comparator: { (first : Any, second : Any) -> ComparisonResult in
    if let f = (first as! RChannels).name, let s = (second as! RChannels).name {
        return f.compare(s)
    } else {
        return .orderedSame
    }
})
于 2016-11-16T07:32:52.933 回答