[英]Swift: how to type cast a protocol into a specific one?
我有一個簡單的代碼如下。 MySprite類(以顯示紅色矩形)是從SKSpriteNode類和協議ISprite擴展的:
import SpriteKit
protocol ISprite {
func doSomething()
}
class MySprite: SKSpriteNode, ISprite {
var scence: SKScene?
init(theParent: SKScene) {
super.init(texture: nil, color: UIColor.redColor(), size: CGSizeMake(300, 300))
self.position = CGPointMake(500, 500)
scence = theParent
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func doSomething() {
}
}
class GameScene: SKScene {
override func didMoveToView(view: SKView) {
var mySprite:SKSpriteNode = MySprite(theParent: self)
self.addChild(mySprite)
}
}
該代碼可以編譯並運行良好。 但是,按照以下方式將mySprite的類型從SKSpriteNode更改為ISprite之后,我無法將其強制轉換/向下轉換回SKSpriteNode:
var mySprite:ISprite = MySprite(theParent: self)
self.addChild(mySprite as? SKSpriteNode!)
快速編譯器顯示錯誤:“類型SKSpriteNode不符合協議ISprite”
對錯誤和解決方案有任何想法嗎? 非常感謝!
addChild期望的SKNode與ISprite不兼容。 它還可以采用SKNode的子類,例如SKSpriteNode。 當mySprite是SKSpriteNode時,Swift可以保證addChild將獲得SKSpriteNode。 將mySprite轉換為SKSpriteNode失敗,因為SKSpriteNode不符合ISprite,因此Swift無法保證它將成為SKSpriteNode。 您可以將mySprite轉換為MySprite,它是SKNode的子類,因此addChild可以使用它:
addChild(mySprite as MySprite)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.