Programming Fundamentals/Conditions/Swift
Appearance
conditions.swift
[edit | edit source]// This program asks the user for a Fahrenheit temperature,
// converts the given temperature to Celsius,
// and displays the results.
//
// References:
// https://www.mathsisfun.com/temperature-conversion.html
// https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html
func getChoice() -> String {
var choice: String
print("Enter C to convert to Celsius or F to convert to Fahrenheit:")
choice = readLine(strippingNewline: true)!
return choice
}
func getTemperature(label: String) -> Double {
var temperature: Double
print("Enter " + label + " temperature:")
temperature = Double(readLine(strippingNewline: true)!)!
return temperature
}
func calculateCelsius(fahrenheit: Double) -> Double {
var celsius: Double
celsius = (fahrenheit - 32) * 5 / 9
return celsius
}
func calculateFahrenheit(celsius: Double) -> Double {
var fahrenheit: Double
fahrenheit = celsius * 9 / 5 + 32
return fahrenheit
}
func displayResult(temperature: Double, fromLabel: String, result: Double, toLabel: String) {
print(String(temperature) + "° " + fromLabel + " is " + String(result) + "° " + toLabel)
}
func main() {
// main could either be an if-else structure or a switch-case structure
var choice: String
var temperature: Double
var result: Double
choice = getChoice()
// if-else approach
if choice == "C" || choice == "c" {
temperature = getTemperature(label:"Fahrenheit")
result = calculateCelsius(fahrenheit:temperature)
displayResult(temperature:temperature, fromLabel:"Fahrenheit", result:result, toLabel:"Celsius") }
else if choice == "F" || choice == "f" {
temperature = getTemperature(label:"Celsius")
result = calculateFahrenheit(celsius:temperature)
displayResult(temperature:temperature, fromLabel:"Celsius", result:result, toLabel:"Fahrenheit")
}
else {
print("You must enter C to convert to Celsius or F to convert to Fahrenheit.")
}
// switch-case approach
switch choice {
case "C", "c":
temperature = getTemperature(label:"Fahrenheit")
result = calculateCelsius(fahrenheit:temperature)
displayResult(temperature:temperature, fromLabel:"Fahrenheit", result:result, toLabel:"Celsius")
case "F", "f":
temperature = getTemperature(label:"Celsius")
result = calculateFahrenheit(celsius:temperature)
displayResult(temperature:temperature, fromLabel:"Celsius", result:result, toLabel:"Fahrenheit")
default:
print("You must enter C to convert to Celsius or F to convert to Fahrenheit.")
}
}
main()
Try It
[edit | edit source]Copy and paste the code above into one of the following free online development environments or use your own Swift compiler / interpreter / IDE.