2015-04-28 38 views
2

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

# 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 

我在斯威夫特什么迄今:

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

*高于雨燕功能unfininshed但你可以看到我的所在地一起去吧。

所以当试图重写这个函数时,我得到了两个erorrs中的一个。不是,因为目前的情况是,我得到:

引用泛型类型“数组”要求论点< ...>

或者,如果我使用INT返回类型改为:

“[INT]”是无法转换为“廉政”

我知道我在斯威夫特利用随机函数是有一定的并发症蟒蛇randint不,但到目前为止,我一直无法追查具体问题。 是我的一个随机整数错误的方法,还是我错误地返回列表? 任何有一些斯威夫特经验的人都有想法吗?在Obj-C中的答案也可能有所帮助。谢谢!

+0

'Array '应该可以工作 – heinst

回答

2

这不是你使用arc4random的问题,没关系。这是因为Swift中的数组内容是键入的,所以你需要返回一个Array<Int>(或者更经常看到,[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大。

+0

你不需要声明两次相同的变量 – heinst

+0

oops剪切和粘贴错字,谢谢,修正。 –