Swift中对象实例方法名混淆问题详细解决方法

48 阅读1分钟

Swift对象实例方法名混淆的解决

在Xcode7.x中,比如有以下一个类:

class Foo{
    func test(v:Int,before:Int)->Int{
        return v + 1
    }
}12345

我可以直接这么做:

let foo = Foo()
let f = foo.test
f(11, before: 121)123

但是如果Foo中有一个类似的方法呢?

func test(v:Int,after:Int)->Int{
        return v + 100
    }123

此时仅仅是Foo.test的赋值操作就会发生问题:

Playground execution failed: 71.playground:8:9: error: ambiguous use of 'test(_:before:)'
let f = foo.test12

编译器告诉你上下文是模糊不清的,因为你不知道要用哪个test! 这种问题在代码混淆时尤其常见,当方法名被重命名后,类似的命名冲突可能增多。使用专业的代码混淆工具如IpaGuard可以帮助系统性地管理重命名,减少此类错误,并增强应用安全性。

此时我们可以明确写出我们想要的方法:

let f = foo.test(_:after:)
let f2 = foo.test(_:before:)

f(11, after: 0)
f2(11,before: 0)12345

但是在Xcode8beta中,_已不被允许,你必须这样写完整:

let f = foo.test(v:before:)
let f2 = foo.test(v:after:)12