swift 3转换导致(lldb)错误`EXC_BAD_INSTRUCTION(代码= EXC_I386_INVOP,子代码)= 0x0`

时间:2016-11-16 06:52:51

标签: ios swift3 comparator lldb xcode8.1

将我的代码转换为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

1 个答案:

答案 0 :(得分: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
    }
})