我可以使 SKSpriteNode 上的初始化失败而不会使应用程序崩溃吗?
Can I make init on SKSpriteNode fail without crashing the app?
我正在通过 for 循环遍历下面的代码。如果某些情况属实,我想“不”创建 SKSpriteNode。是否有特定的 return,即 -1,我可以调用它来导致 SKSpriteNode 不被创建,而不会使应用程序崩溃?
或者这是我在创建它之前需要弄清楚的事情吗?
class GuessSlot : SKSpriteNode{
var nodeIndex : Int
var holdingGem : Bool = false
init(color: SKColor, size: CGSize, width: CGFloat, iFactor: Int, guessBarRef: GuessBar){
let skTexture = SKTexture(imageNamed: "gem_slot")
self.nodeIndex = iFactor
super.init(texture: skTexture, color: color, size: size)
self.name = "slot"
self.size.width = size.width
self.size.height = size.width
self.anchorPoint = CGPoint(x: 0.5, y: 0.5)
var indexSpacing = (size.width * CGFloat(iFactor)) +
((size.height * 2) * CGFloat(iFactor)) + (size.width/2)
indexSpacing += 10
self.position = CGPoint(x: indexSpacing, y: guessBarRef.size.height/2)
self.isHidden = false
guessBarRef.addChild(self)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
看来您可能想要 failable initializer。这将 return nil
(意思是“无”,有点像 -1
)。
init?(color: SKColor, size: CGSize, width: CGFloat, iFactor: Int, guessBarRef: GuessBar) {
if /* your condition here */ {
return nil
}
}
然后您可以像这样使用它:
if let slot = GuessSlot(color: ..., size: ..., width: ..., iFactor: ..., guessBarRef: ...) {
/// `SKSpriteNode` has been created
} else {
/// won't crash app and `SKSpriteNode` is not created
}
我正在通过 for 循环遍历下面的代码。如果某些情况属实,我想“不”创建 SKSpriteNode。是否有特定的 return,即 -1,我可以调用它来导致 SKSpriteNode 不被创建,而不会使应用程序崩溃?
或者这是我在创建它之前需要弄清楚的事情吗?
class GuessSlot : SKSpriteNode{
var nodeIndex : Int
var holdingGem : Bool = false
init(color: SKColor, size: CGSize, width: CGFloat, iFactor: Int, guessBarRef: GuessBar){
let skTexture = SKTexture(imageNamed: "gem_slot")
self.nodeIndex = iFactor
super.init(texture: skTexture, color: color, size: size)
self.name = "slot"
self.size.width = size.width
self.size.height = size.width
self.anchorPoint = CGPoint(x: 0.5, y: 0.5)
var indexSpacing = (size.width * CGFloat(iFactor)) +
((size.height * 2) * CGFloat(iFactor)) + (size.width/2)
indexSpacing += 10
self.position = CGPoint(x: indexSpacing, y: guessBarRef.size.height/2)
self.isHidden = false
guessBarRef.addChild(self)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
看来您可能想要 failable initializer。这将 return nil
(意思是“无”,有点像 -1
)。
init?(color: SKColor, size: CGSize, width: CGFloat, iFactor: Int, guessBarRef: GuessBar) {
if /* your condition here */ {
return nil
}
}
然后您可以像这样使用它:
if let slot = GuessSlot(color: ..., size: ..., width: ..., iFactor: ..., guessBarRef: ...) {
/// `SKSpriteNode` has been created
} else {
/// won't crash app and `SKSpriteNode` is not created
}