2

I am trying to get a random string from array "firstArray" and print it in UILabel "label". I cannot seem to figure it out and I get errors. Your help is appreciated. I tried searching but could not find any up-to-date tutorials/methods.

import UIKit

class ViewController: UIViewController {
    @IBOutlet var label: UILabel!

    @IBAction func random(_ sender: Any) {
        let firstArray = [ "hi" , "bye" , "hello"]
    }
5
  • 1
    Update your question with the code causing the error and post the error message. Commented Dec 21, 2016 at 6:29
  • your question is not a really bad question, so i won't downvote it. But you really need to post more info, like how you implement the 'random' function. (cause i do not see any random algo. from you code, you just defined a array of string) Commented Dec 21, 2016 at 6:31
  • analyses the code before post for proper basic opening and closing brackets at least. Commented Dec 21, 2016 at 6:33
  • 1
    This might be what you are looking for: Pick a random element from an array. Commented Dec 21, 2016 at 6:34
  • One tip to improve your code is, don't name your IBAction method random, you see people don't even know where you want to implement the random function. Write another function called random, then put it inside that IBAction, it'll be easier for you to read later on :) Commented Dec 21, 2016 at 6:39

2 Answers 2

3

I'd rather using arc4random(), this code will pick up random items from your array:

let firstArray = ["hi", "bye", "hello"]
    let randomItem = Int(arc4random() % UInt32(firstArray.count))
    myLabel.text = "\(firstArray[randomItem])"
Sign up to request clarification or add additional context in comments.

5 Comments

This makes no attempt to get a random value from the array and it assigns the random Int to the label.
yep, mistyped error, i've forgot the firstArray[] before (randomItem) :)
Please avoid posting code-only answers. Try to explain how your code solves the OP's problem, and help others who are less experienced understand your solution.
While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.
@fvimagination its not working in swift 4 would you provide an update?
1

You have to generate random numbers between 0 and your array count, then set the label text to the corresponding item in array, like this:

@IBAction func random(_ sender: UIButton) {
     let firstArray = [ "hi" , "bye" , "hello"]
     var randomNumber = Int(arc4random_uniform(UInt32(firstArray.count)))
     randLabel.text = firstArray[randomNumber]
}

this thread is helpful to understand the random logic.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.