My Swift Journey (Slowly but surely)

I know, the following code is probably basic for everyone in here but I am feeling a bit accomplished for finally figuring it out and wanted to share. Background… started reading a Swift for beginners book & the first challenge/exercise was to create some code for a user to guess a number from 1 - 10. I was lost! Thankfully, I stumbled across the Coding with Chris videos which I have been slowly working through. Today, I thought I would give the 1-10 guessing game another shot &, with with the help of some Google searches, I was able to do the following. Slowly but surely…

//

// main.swift

// GuessANumber

//

// Created by Arnie Gumieny on 2020-07-05.

// Copyright © 2020 Arnie S. Gumieny. All rights reserved.

//

import Foundation

print(“Do you want to play a game?”)

var guess = 0

//Generate random number between 1 & 10

let number = Int.random(in: 0 … 10)

//print(number)

while guess != number {

//Ask player to guess a number from 1 to 10

let fh = FileHandle.standardInput

print(“Please guess a number from 1 to 10.”)

let num1 = fh.availableData

if let numString1 = NSString(data: num1, encoding: String.Encoding.utf8.rawValue) {

let val1 = numString1.integerValue

guess = val1

//print (“You guessed (guess)”)

}

//Compare random number to guessed number

if guess != number {

print(“Sorry, you guessed wrong. Try again.”)

}else {

print (“Correct! The random number was (number).”)

}

}

2 Likes

Awesome work and kudos for sticking with it !!

Excellent work! Well done.