簡體   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