我正在尝试使全局findAndRemove函数与ArrayType一起使用,并且遇到了问题。我收到一个错误消息:

Cannot convert the expression's type '0' to type '@lvalue Named'

这是功能...

func findAndRemove<C : ArrayType where C.GeneratorType.Element : Equatable>(var domain: C, value: C.GeneratorType.Element) {
  var idx = find(domain, value)
  if idx { domain.removeAtIndex(idx! as Int) }
}


这是您可以放入Xcode游乐场的随附的人工代码...

class Named {
  let name: String
  init (_ name: String) {
    self.name = name
  }
}

var arr = [Named("Fire"), Named("Water"), Named("Earth"), Named("Air")]
var fire = arr[0]

arr // Returns [Named("Fire"), Named("Water"), Named("Earth"), Named("Air")]
findAndRemove(&arr, fire) // <-- Error occurs here!!!
arr // Should return [Named("Water"), Named("Earth"), Named("Air")]


不必担心该示例没有意义,因为我只能使用arr.removeAtIndex(0)。这是测试findAndRemove的人为例子。

最佳答案

解决方案是使用符合Equatable协议的协议:

class Named {
    let name: String
    init (_ name: String) {
        self.name = name
    }
}

extension Named : Equatable { }

func ==(lhs: Named, rhs: Named) -> Bool {
    return lhs.name == rhs.name
}




现在此功能应该可以正常使用(改为使用inout var):

func findAndRemove<C : ArrayType where C.GeneratorType.Element : Equatable>(inout domain: C, value: C.GeneratorType.Element) -> () {
    var idx = find(domain, value)
    if idx { domain.removeAtIndex(idx! as Int) }
}




我也用最后的电话扩展了答案:

var myArray: Array<Named> = [Named("Fire"), Named("Water"), Named("Earth"), Named("Air")]
var fire: Named = myArray[0]

findAndRemove(&myArray, value: fire)

关于ios - ArrayType findAndRemove全局函数出错?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24142115/

10-09 01:40