如何调用模糊方法?

时间:2014-06-07 12:41:13

标签: swift xcode6

给出此代码

extension Array {
    func filter(includeElement: (T) -> Bool) -> T[] {
        var ret = T[]()
        for e in self {
            if includeElement(e) {
                ret += e
            }
        }
        return ret
    }
}

var a = [1,2]
var b = a.filter() {i in print(i); return true}

无法使用错误消息进行编译

error: ambiguous use of 'filter'
var b = a.filter() {i in print(i); return true}
        ^
Swift.Array<T>:84:8: note: found this candidate
  func filter(includeElement: (T) -> Bool) -> Array<T>
       ^
<REPL>:30:10: note: found this candidate
    func filter(includeElement: (T) -> Bool) -> T[] {
         ^

所以看起来我可以创建带有重复方法和签名的扩展方法,但我不知何故需要一种特殊的方法来调用它


BTW,默认Array.filter被破坏,它为每个元素调用两次闭包并且崩溃REPL或者如果结果不一致则在操场上给出你的垃圾结果

xiliangchen-imac:~ xiliangchen$ xcrun swift
Welcome to Swift!  Type :help for assistance.
  1> let arr = [1,2,3,4,5]
arr: Int[] = size=5 {
  [0] = 1
  [1] = 2
  [2] = 3
  [3] = 4
  [4] = 5
}
  2> var i = 0
i: Int = 0
  3> let arr2 = arr.filter() {
  4.         println($0)
  5.         return i++ < 5
  6. }   
Segmentation fault: 11

1 个答案:

答案 0 :(得分:2)

我认为定义含糊不清的方法没有问题。当您从不同模块导入 2个ambiguos方法时,会出现问题。不幸的是,如何排除Array.filter被导入。

我做了一些测试,在我看来,没有明确定义具有明确定义的定义的行为,例如:

extension NSString {
    func hasPrefix(aString: String!) -> Bool {
        return false
    }
}

let string: NSString = "test"

var hasPrefix = string.hasPrefix("t")
println("Has prefix: \(hasPrefix)") //prints "true"

var method = string.hasPrefix
hasPrefix = method("t")

println("Has prefix: \(hasPrefix)") //prints "false"

obj-c类的行为可能不同......

对于函数,似乎优先选择当前模块的定义:

func NSStringFromCGPoint(point: CGPoint) -> String! {
    return "My method"
}

var point = CGPoint(x: 10.0, y: 10.0)

println("Point: \(NSStringFromCGPoint(point))") //Prints "My method"
println("Point: \(UIKit.NSStringFromCGPoint(point))") //Prints "{10, 10}"