Create a OSX command line application, using Swift as the language. Once the project is created, create a new Swift file (using File - New - File) and name it BingoMachine.swift
import
statement, add the following code to declare a new class:
class BingoMachine {
}
//declare a tumbler (keep private)
private var tumbler: [Int]
//declare the board (this will be public)
var calledNumbers: [Int]
This declares two arrays of integers (but does not create them)
init(){
//instantiate the tumbler and called numbers arrays
tumbler = [Int]()
calledNumbers = [Int]()
//add balls to tumbler
for i in 1...90{
tumbler.append(i)
}
}
Whenever we create a new BingoMachine using BingoMachine()
the init method will be called, instantiating the two arrays, and placing the numbers in the tumbler
func getNumber() -> Int{
//to use the random function, which requires an unsigned 32 bit integer,
//we need to convert the number of balls in the tumbled to this format
let positionUInt = UInt32(tumbler.count)
//then convert the result of calling the random number function
//back to Swift's 'Int' type (64 bit signed)
let position = Int(arc4random_uniform(positionUInt))
//get the number at the random position
let number = tumbler[position]
//remove it from the tumbler array
tumbler.remove(at:position)
//place it in the called numbers array
calledNumbers.append(number)
//return the number
return number
}
true
or false
value. Add the function below to do that:
func ballsRemaining() -> Bool{
return tumbler.count > 0
}
import
, and add the following code:
//create a new instance of the BingoMachine class
var bingoMachine = BingoMachine()
//while there are balls remaining
while bingoMachine.ballsRemaining(){
//print out the number, followed by a comma and space
print(bingoMachine.getNumber())
print(", ")
}
It's likely that we may want to check if a number has been called - we can do this by checking for its existence in the calledNumbers array. One way to do so would be to loop the the array and compare values, however swift provides a generic function to check if a sequence contains an value, the method is simply contains()
. Add the function shown below to the BingoMachine class to do just that:
func hasCalled(number: Int) -> Bool{
return calledNumbers.contains(number)
}
To test this add the code below to the bottom of the while
loop in main.swift:
let luckyNumber = 7;
if bingoMachine.hasCalled(number: luckyNumber){
print("Lucky number \(luckyNumber) found")
break
}