iOS Swift:如何将以下Objective C方法移植到Swift?

时间:2015-03-16 19:18:28

标签: ios objective-c swift

我正在学习斯威夫特并试图了解所有目标并了解它。

这是我试图移植到Swift的Objective C代码。

NSInteger sort(id num1, id num2, void *context) {
int v1 = [num1 intValue];
int v2 = [num2 intValue];
if (v1 < v2)
 return NSOrderedAscending;
else if (v1 > v2)
return NSOrderedDescending;
else
return NSOrderedSame;
}

这是我到目前为止所做的。

func sort (num1 : AnyObject , num2 : AnyObject , context : Void) -> NSInteger

{
    var v1 : Int = num1.integerValue
    var v2 : Int = num2.integerValue


    if (v1 < v2) {
        return NSOrderedAscending
    }
    else if (v1 > v2) {
        return NSOrderedDescending
    }
    else {
        return NSOrderedSame
    }
}

这种方法的问题是NSOrderedAscending似乎不存在,我相信我的方法名称都是错的。任何提示或建议都表示赞赏。

3 个答案:

答案 0 :(得分:5)

这个功能很危险,在ObjC中有点令人惊讶。这在Swift中是非常令人惊讶的,并且不太可能非常有用。

在ObjC中,这主要是重新实现compare:。它传递id而不是某种特定类型(NSString可能?)的事实使得它非常危险。没有承诺intValue在您传递的内容上实施。在Swift中,传递正确的类型更为重要。但无论如何,通过接受闭包或函数,无论调用什么都可能会做得更好。目前还不清楚目标是什么。

您移植context不正确。 Void不等于void*。它等于(),这是完全不同的。您没有使用上下文这一事实表明您可能应该避免移植它,并且只需将调用代码重新编写为更像Swift的类型。

将ObjC代码机械转换为Swift很可能会造成非常糟糕的Swift。特别是,如果您经常使用AnyObject,那么您可能做错了。

答案 1 :(得分:2)

在Swift中,返回值是这样写的:

NSComparisonResult.OrderedAscending
NSComparisonResult.OrderedDescending
NSComparisonResult.Same

答案 2 :(得分:1)

有几个问题使直接端口变得非常重要。

首先,Objective-C代码调用对象上的intValue方法。这表明传递给函数的对象应该是NSString个实例,因此Swift函数应该采用NSString个参数,而不是AnyObject个参数(除非函数真的可以采取任何类型的对象,在这种情况下请参阅下面的注释。此外,context参数根本没有被使用,所以它并不是必需的。此外,返回类型实际上是NSComparisonResult,而不是NSInteger。鉴于此,Swift版本看起来像:

func sort(num1: NSString, num2: NSString) -> NSComparisonResult {
    let v1 = num1.intValue
    let v2 = num2.intValue
    if v1 < v2 {
        return NSComparisonResult.OrderedAscending
    } else if v1 == v2 {
        return NSComparisonResult.Same
    } else {
        return NSComparisonResult.OrderedDescending
    }
}

如果Swift版本确实 需要对任何类型的对象进行操作,那么最好使用条件转换:

func sort(num1: AnyObject, num2: AnyObject) -> NSComparisonResult {
    if let n1 = num1 as? NSString {
        if let n2 = num2 as? NSString {
            let v1 = n1.intValue
            let v2 = n2.intValue
            if v1 < v2 {
                return NSComparisonResult.OrderedAscending
            } else if v1 > v2 {
                return NSComparisonResult.OrderedDescending
            }
        }
    }
    return NSComparisonResult.Same
}