Using functions in arrays Swift

70 views Asked by At

i use the following function to retrieve a random person from an array:

func getRandomPerson() -> String{

if(personArray.isEmpty){
    return ""
} else {
    var tempArray: [String] = []
    for person in personArray{
        tempArray += [person.getName()]
    }
    var unsignedArrayCount = UInt32(tempArray.count)
    var unsignedRandomNumber = arc4random_uniform(unsignedArrayCount)
    var randomNumber = Int(unsignedRandomNumber)
    if tempArray.isEmpty {
        return ""
    } else {
        return tempArray[randomNumber]
    }
}
}

I would like to use this function inside an array of strings, Like this:

 var theDares: [String] = ["Dare1 \(getRandomPerson())", "Dare2", "Dare3", "Dare4", "Dare5"]

But when i use the functions, it only runs the function once. Can you make the function run everytime you use the "Dare1" in this instance.

Thanks in advance

2

There are 2 answers

0
Duncan C On BEST ANSWER

I think you are asking if you can set up your array so every time you fetch the object at index 0, it re-builds the value there.

The short answer is no. Your code is creating an array of strings, and the item at index 0 is built ONCE using a function call.

However, it is possible to make a custom class implement the subscript operator. You could create a custom object that looks like an array and allows you to index into it using an Int index. In response to the index operator you could run custom code that built and returned a random string.

Since it sounds like you're a beginning programmer creating a custom class the implements the subscript operator might be beyond your current abilities however.

0
Leo Dabus On

Try like this:

let personArray = ["John", "Steve", "Tim"]

var randomPerson: String {
    return personArray.isEmpty ? "" : personArray[Int(arc4random_uniform(UInt32(personArray.count)))]
}


println(randomPerson)   // "Steve"