mardi 28 avril 2015

Returning a List of Integers in Swift

I am an amateur Python programmer trying my hand at Apple's new Swift programming language. I recently decided to rewrite a Python script I have in Swift as a first step towards building this out into an iOS app. I ran into a bit of a challenge that so far I have been unable to resolve. In Python I have a function that returns a list of random integers:

# 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

What I have in Swift thus far:

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

*That Swift function above is unfininshed but you can see where I am going with it.

So when trying to rewrite this function I get one of two erorrs. Either, as it stands now, I get:

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

Or, if I use the Int return type instead:

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

I know that the random function I am utilizing in Swift is has some complications that Pythons randint doesn't but so far I have been unable to track down the specific issue. Is my method of a random integer in error or am I returning the list incorrectly? Anyone with some Swift experience have an idea? Answers in Obj-C may also be helpful. Thanks!




Aucun commentaire:

Enregistrer un commentaire