gpt4 book ai didi

swift - 在 Swift 中使用 Rand 进行测试

转载 作者:行者123 更新时间:2023-11-28 10:30:23 30 4
gpt4 key购买 nike

我想测试我的“Roll Dice”功能,然后生成游戏的当前运行分数。

签名是:

func rollDice(randFunc: ((ClosedRange<Int>) -> Int)? = Int.random) -> (dice1: Int, dice2: Int, losePointsTurn: Bool, losePointsGame: Bool)

因为我想换出随机函数,所以我可以测试它,随机函数是通过以下方式调用的:

dice1 = randFunc!(0...5)
dice2 = randFunc!(0...5)

我在测试目标中为非随机函数创建了一个扩展

extension ClosedRange {
func noRand(_ : Bool) -> Int {
return 0
}
}

但是当我尝试在测试中使用它时:

gm.rollDice(randFunc: ClosedRange<Int>.noRand)

我有错误:

Cannot convert value of type '(ClosedRange) -> (Bool) -> Int' to expected argument type '((ClosedRange) -> Int)?'

那么如何编写一个非随机的随机函数来交换这个函数呢?

最佳答案

在您的示例代码中,noRand应该是一个接受 ClosedRange 的函数并返回 Int .

没有理由让它成为 ClosedRange 的扩展.此外,您可以随意查看 Int.random 的签名静态方法,本质上是复制粘贴。

它的签名是(ClosedRange<Int>) -> Int , 标注为 random(in:) .你的noRand函数必须具有相同的签名。

因此,这给我们留下了

func noRand(in range: ClosedRange<Int>) -> Int {
return 0
}

请注意,它不需要作为 ClosedRange 的扩展名.考虑到您只会在测试中使用它,您不妨在范围级别声明。

关于swift - 在 Swift 中使用 Rand 进行测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56422981/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com