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 trial

iOS Build a Simple iPhone App with Swift Improving Our User Interface Adapting Our Content

Matt George
Matt George
2,507 Points

Trying to make a COIN TOSS app but my code isn't working! Please help?!

import UIKit

class ViewController: UIViewController {

struct Formula {
    let tossArray = ["Heads","Tails"]


    func probability() -> String {
        let unsignedTossArray = UInt32(tossArray.count)
        let unsignedRandomNumber = arc4random_uniform(unsignedTossArray)
        var randomProbaility = Int(unsignedRandomNumber)

        return tossArray[randomProbaility]
    }
}

let formula = Formula()

@IBOutlet weak var tossAnswer: UILabel!

  override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    tossAnswer.text = "Heads or Tails?"
}
override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
@IBAction func headsOrTails(sender: AnyObject) {
    tossAnswer.text = formula.probability()      
}    

}

1 Answer

Sam Chaudry
Sam Chaudry
25,519 Points

Hi Matt I've had a quick rebuild of the coin toss app and got a working version. I've added my code below and annotated at the top so you can see how I have done it.

//1. Create model Swift file in my case I've called it Coin.swift

//2. Add Coin Struct and it's values struct CoinResults {

let tossArray = ["Heads","Tails"];

func tossTheCoin()->String{

    let unsignedTossArray = UInt32(tossArray.count)
    let unsignedRandomNumber = arc4random_uniform(unsignedTossArray)
    var randomProbaility = Int(unsignedRandomNumber)

    return tossArray[randomProbaility]

}

//3. Go into viewcontroller

class ViewController: UIViewController {

//Create your results label @IBOutlet weak var results: UILabel!

//Create your button @IBAction func CoinToss(sender: AnyObject) {

//Call the Swift Struct CoinResults

    let Coins = CoinResults();

//Set the properties of your results text label to call the struct's tossTheCoin method ad this will return heads or tails
results.text = Coins.tossTheCoin();

}


override func viewDidLoad() {

    super.viewDidLoad()

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

}

I hope this helps.

Sam