Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialAlexis Marrero
4,275 PointsHow to make my label show the words but now randomly i want the words to show in order. SWIFT 4
let words = ["Cat", "Dog", "Bird", "Butterfly", "Fish"]
//variables
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func showWord(_ sender: Any) {
let randomIndex = Int(arc4random_uniform(UInt32(words.count)))
// Set the text at the randomIndex as the text of the label
englishLabel.text = words[randomIndex]
}
2 Answers
Jeff McDivitt
23,970 PointsThe way you have this set up it will not even show random words?
To show random words the correct way it would look like the below:
import UIKit
import GameKit
class ViewController: UIViewController {
let words = ["Cat","Dog","Bird","Butterfly", "Fish"]
@IBOutlet weak var showLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func randomWords() -> String {
let randomNumber = GKRandomSource.sharedRandom().nextInt(upperBound: words.count)
return words[randomNumber]
}
@IBAction func showWord(_ sender: Any) {
showLabel.text = randomWords()
}
}
I did a few things different from your code (which I believe your code will not run)
- Import GameKit 2 Create a function to handle the randomization
Let me know if you have any other questions :)
Jeff McDivitt
23,970 PointsIn order like the same order you have them in the Array?
Alexis Marrero
4,275 PointsAlexis Marrero
4,275 PointsIm so sorry i meant the opposite i want to make my label show words in order not random . Can you help me please ??