返回 Swift 中的整数列表

Returning a List of Integers in Swift

我是一名业余 Python 程序员,正在尝试使用 Apple 的新 Swift 编程语言。我最近决定重写 Swift 中的 Python 脚本,作为将其构建到 iOS 应用程序的第一步。我 运行 遇到了一个挑战,到目前为止我一直无法解决。在 Python 中,我有一个函数 return 是 运行dom 整数的列表:

# Roll the Attackers dice in Python
def attacker_rolls(attack_dice):
    attacker_roll_result = []
    if attack_dice >= 3:
        attacker_roll_result += [randint(1,6), randint(1,6), randint(1,6)]
    elif attack_dice == 2:
        attacker_roll_result += [randint(1,6), randint(1,6)]
    elif attack_dice == 1:
        attacker_roll_result = [randint(1,6)]
    attacker_roll_result.sort(reverse=True)
    print "The attacker rolled: " + str(attacker_roll_result)
    return attacker_roll_result

到目前为止,我在 Swift 中拥有的内容:

// Roll the attackers dice in Swift
func attackerRolls(attackDice: Int) -> Array {
    if attackDice >= 3 {
        var attackerRollResult = [Int(arc4random_uniform(6)+1), Int(arc4random_uniform(6)+1), Int(arc4random_uniform(6)+1)]
        return attackerRollResult
    }
}

*上面的 Swift 函数尚未完成,但您可以看到我要用它做什么。

因此,在尝试重写此函数时,我遇到了两个错误之一。或者,就目前而言,我得到:

Reference to generic type 'Array' requires arguments in <...>

或者,如果我改用 Int return 类型:

'[Int]' is not convertible to 'Int'

我知道我在 Swift 中使用的 运行dom 函数有一些复杂性,而 Pythons 运行dint 没有,但到目前为止我有无法追查具体问题。 我的 运行dom 整数方法是错误的还是我 return 列表不正确? 有 Swift 经验的人有想法吗? Obj-C 中的答案也可能有帮助。谢谢!

这不是您使用 arc4random 的问题,没关系。这是因为 Swift 中数组的内容是类型化的,所以你需要 return 一个 Array<Int> (或者更常见的是, [Int] 这是同一事物的语法糖) .

如果你修复了这个问题,你会得到一个不同的编译错误,因为所有代码路径都必须 return 一个值,所以请尝试以下操作:

// Roll the attackers dice in Swift
func attackerRolls(attackDice: Int) -> Array<Int> {
    var attackerRollResult: [Int]
    if attackDice >= 3 {
        attackerRollResult = [Int(arc4random_uniform(6)+1), Int(arc4random_uniform(6)+1), Int(arc4random_uniform(6)+1)]
    }
    else {
        attackerRollResult = [Int(arc4random_uniform(6)+1)]
    }
    return attackerRollResult
}

对于此用例,您可能还想研究使用 switch 而不是 if