在测试时,Struct方法每隔一次运行返回不同的值

时间:2014-12-18 14:43:50

标签: ios swift

这种奇怪行为可能是什么原因。我在属于struct的方法中有以下六个常量。

    let crossSouthWest1 = getCrossProduct(x, y: y, from: .SouthWest)
    let crossSouthWest2 = getCrossProduct(x, y: y, from: .SouthWest)
    let crossSouthWest3 = getCrossProduct(x, y: y, from: .SouthWest)
    let crossSouthWest4 = getCrossProduct(x, y: y, from: .SouthWest)
    let crossSouthWest5 = getCrossProduct(x, y: y, from: .SouthWest)
    let crossSouthWest6 = getCrossProduct(x, y: y, from: .SouthWest)

在为struct创建单元测试时,我遇到了这种奇怪的行为,我得到nil返回有效输入的值。所以我放置了breakpoint和单个方法调用的垃圾邮件副本,这就是我得到的。

bizarre

请注意,相同的代码会在操场上以完全相同的输入产生所需的结果。

playground

以下是相关方法:

func getCrossProduct(x: Int, y: Int, from planarDirection: PlanarDirection) -> Float3? {
    let u = getAdjacentVertex(x, y: y, from: planarDirection.cardinalDirections.0)
    let v = getAdjacentVertex(x, y: y, from: planarDirection.cardinalDirections.1)

    if let vNotNil = v {
        if let uNotNil = u {
            let from = getVertex(x, y)
            let toU = uNotNil.subtract(from)
            let toV = vNotNil.subtract(from)

            return toU.crossProductWith(toV)
        }
    }
    return nil
}

这是getAdjacentVertex的代码。

func getAdjacentVertex(x: Int, y: Int, from direction: Direction) -> Float3? {
    let modifierX       = (direction == .West) ? 1 : 0
    let modifierWidth   = (direction == .East) ? -1 : 0
    let modifierY       = (direction == .North) ? 1 : 0
    let modifierHeight  = (direction == .South) ? -1 : 0

    if x >= modifierX &&
        x < width + modifierWidth &&
        y >= modifierY &&
        y < height + modifierHeight {
        return getVertex(x - modifierX - modifierWidth, y - modifierY - modifierHeight)
    }
    return nil
}

更新

我已从这些方法中删除了所有变量,但结果保持不变。

0 个答案:

没有答案