【问题标题】:Returning a List of Integers in Swift在 Swift 中返回整数列表
【发布时间】:2015-07-07 13:37:27
【问题描述】:

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

# 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 函数还没有完成,但你可以看到我的目标。

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

对泛型“数组”的引用需要 <...>

中的参数

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

'[Int]' 不能转换为 'Int'

我知道我在 Swift 中使用的随机函数有一些复杂性,而 Python randint 没有,但到目前为止我还无法找到具体问题。 我的随机整数方法是错误的还是我错误地返回了列表? 有一些 Swift 经验的人有一个想法吗? Obj-C 中的答案也可能会有所帮助。谢谢!

【问题讨论】:

  • Array&lt;Int&gt; 应该可以工作

标签: python list swift random integer


【解决方案1】:

这不是你使用arc4random 的问题,没关系。这是因为 Swift 中数组的内容是有类型的,所以你需要返回一个 Array&lt;Int&gt;(或者更常见的是 [Int],它是同一事物的语法糖)。

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

// 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

【讨论】:

  • 同一个变量不需要声明两次
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-10-28
  • 1970-01-01
  • 2016-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多