sabi
sabi

Reputation: 423

How to define a function in Swift without running it

Starting from the Simple C program found here on stackoverflow, I've done it again in Swift and here's the code:

import Foundation

// variables and constants:

var dice1, dice2: UInt32
var score, scoreToWin, diceSum: Int
dice1 = 0
dice2 = 0
diceSum = 0

// functions:

func rollDice() ->Int {
  dice1 = arc4random() % 6 + 1
  dice2 = arc4random() % 6 + 1
  diceSum = Int(dice1 + dice2)
  println("\(diceSum)")
  return diceSum
}

// main:

score = rollDice()

println("\(dice1) \(dice2) \(score)")

switch score {
  case 7, 11:
    println("score=\(score)\nYou WIN")
  case 2, 3, 12:
    println("score=\(score)\nYou LOOSE")
  default:
    println("You have to roll a \(score) to WIN")
    do {
      scoreToWin = score
      diceSum = rollDice()
    if diceSum == 7 { println("You LOOSE") }
    else if diceSum == scoreToWin { println("You WIN") }
    } while (diceSum != scoreToWin && diceSum != 7)
}

This is a possible output:

I was not expecting the first line of output, because the first line indicate the function rollDice() was run while been defined. How can I define a function without actually running it?

Upvotes: 1

Views: 79

Answers (1)

Klaus Byskov Pedersen
Klaus Byskov Pedersen

Reputation: 120997

score = rollDice() would print the 6 you are seeing due to the println("\(diceSum)") you are doing in the rollDice method.

Declaring a method does not run it. Not in swift, nor in any other language I can think of.

Upvotes: 5

Related Questions