与该ActionScript函数等效的Swift

时间:2018-10-05 11:02:42

标签: ios swift actionscript-3

我将此tutorial on BSP译为很快的书。在本教程中,有此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编写?

1 个答案:

答案 0 :(得分:2)

您的问题是您正在强制解开MyCache的结果-此函数返回一个可选值,并且当遍历到达叶节点时可以合法地返回final case class MyCache[CacheRepr <: InMemoryRepr | Array[Byte]](scalaCache: ScalaCache[CacheRepr]) 。强制展开func createDatePickerDgeb1() { datePickergeb.datePickerMode = .date let toolbar = UIToolbar() toolbar.sizeToFit() let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector(donePressedgeb1)) let spaceButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) toolbar.setItems([spaceButton,doneButton], animated: false) gebdatum.inputAccessoryView = toolbar gebdatum.inputView = datePickergeb } results in a crash

通过正确使用条件解包,不仅可以使代码更具可读性,而且可以避免崩溃。

getRoom