繁体   English   中英

类型“T”不符合协议“AnyObject”

[英]Type 'T' does not conform to protocol 'AnyObject'

我正在 Swift 中创建一个 IOS 应用程序,它具有从屏幕右侧移动到屏幕左侧的块。 在它消失后我想删除它。 这是块类:

class Block : BasicObject {

    var type : Int
    var velocity = CGVectorMake(-playerVelocityY, -playerVelocityY)

    init(x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat, type: Int) {
        self.type = type
        super.init(x : x, y : y, width : width, height : height)
    }

    func update() {

        self.position.x += self.velocity.dx

        if self.position.x + self.size.width < 0 {
            blocks.removeObject(self) // <-- line of code to delete object from list
        }

    }

}

它继承自 BasicObject 类:

class BasicObject {
    var position : CGPoint
    var size : CGSize
    init (x : CGFloat, y : CGFloat, width : CGFloat, height : CGFloat){
        self.position = CGPointMake(x, y)
        self.size = CGSizeMake(width, height)
    }
} 

现在在我的 Block Class 中有一行代码:

blocks.removeObject(self)

那行代码指的是:

var blocks : [Block] = []

extension Array {
    func removeObject<T>(object: T) {
        for items in self {
            if self[items] === object { // <-- Error occurs on this line
                self.removeAtIndex(items)
            }
        }
    }
}

由于某种原因,错误:类型“T”不符合协议“AnyObject”。 有人可以解释为什么会发生这种情况并提供一个如何解决它的例子。 或者,如果有人甚至可以提供一种更简单的方法来从 blocks 数组中删除 Block 对象。

这里的东西很少。 所有的数组首先是结构,所以你不能修改的方法内容没有使它变异方法。 另一件事是,除非它们符合Comparable协议,否则如何将一个T对象与另一个对象进行比较

我在您的示例方法 removeObject 中修改了一些内容,

extension Array where T:Comparable{
    mutating func removeObject(object: T) {
        for (index, item) in self.enumerate() {
            if item == object {
                self.removeAtIndex(index)
                break
            }
        }
    }
}

顺便说一下,你可以用 Swift *indexOf** 和removeAtIndex方法做同样的事情。

extension Array where T:Comparable{
    mutating func removeObject(object: T) {
        while  let index =  indexOf(object) {
            removeAtIndex(index)
        }
    }
}

数组是值类型,所以修改需要将函数声明为mutating 同时将通用接口声明为Equatable进行比较,并检查相同类型的运算符。

extension Array {
  mutating func removeObject<T: Equatable>(value: T) {
    for (index, item) in enumerate(self) {
      if let item = item as? T where item == value {
        removeAtIndex(index)
        return
      }
    }
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM