【发布时间】:2018-10-05 11:02:41
【问题描述】:
我将这个tutorial on BSP 翻译成swift。在教程中有这个 ActionScript 函数。
public function getRoom():Rectangle
{
// iterate all the way through these leafs to find a room, if one exists.
if (room != null)
return room;
else
{
var lRoom:Rectangle;
var rRoom:Rectangle;
if (leftChild != null)
{
lRoom = leftChild.getRoom();
}
if (rightChild != null)
{
rRoom = rightChild.getRoom();
}
if (lRoom == null && rRoom == null)
return null;
else if (rRoom == null)
return lRoom;
else if (lRoom == null)
return rRoom;
else if (FlxG.random() > .5)
return lRoom;
else
return rRoom;
}
}
我将这个函数翻译成 Swift(尽我所能)我一定是写错了,因为该函数在不应该返回一个 nil 值。
我的 Swift 版本:
// left/right child are initialized as follows:
// leftChild:Room?
// rightChild:Room?
public func getRoom() -> Room? {
if room != nil {
return room
} else {
var lRoom:Room?
var rRoom:Room?
if leftChild != nil {
lRoom = leftChild!.getRoom()!
}
if rightChild != nil {
rRoom = rightChild!.getRoom()!
}
if lRoom == nil && rRoom == nil {
return nil
} else if rRoom == nil {
return lRoom
} else if lRoom == nil {
return rRoom
} else if Double.random(in: 0..<1.0) > 0.5 {
return lRoom
} else {
return rRoom
}
}
}
Room 是我为帮助我处理房间而制作的基本类。
class Room {
var x1:Int
var x2:Int
var y1:Int
var y2:Int
var center:CGPoint
init(X: Int, Y: Int, W: Int, H: Int) {
x1 = X
x2 = X + W
y1 = Y
y2 = Y + H
center = CGPoint(x: (x1 + x2) / 2, y: (y1 + y2) / 2)
}
}
我不应该得到一个 nil 值。我想我把函数翻译错了。 Rectangle 在 Swift 中将是 CGRect,但我在代码的其他地方用我的 Room 类替换了它,所以我知道它可以在这里与 Room 类一起使用。
如何用 Swift 编写这个函数?
【问题讨论】:
-
您正在强制解开
getRoom的结果,它可以返回nil。 -
我必须强制打开它,否则它不会让我使用该功能。我想我把函数翻译错了,但我不确定在哪里。重复的问题不是我的问题。
-
不,您必须有条件地打开它。您的遍历在叶节点处合法地返回
nil。强制展开nil会产生异常。副本解释了您为什么会崩溃。 -
我的函数写错了。 ActionScript 函数的工作方式与我编写的版本不同。我试图弄清楚我写错了什么,而不是为什么函数返回 nil。我编辑了问题以澄清我的问题。
-
除了强制解包问题之外,您的代码是 ActionScript 的合理翻译。
标签: ios swift actionscript-3