Skip to main content
Engineering LibreTexts

3.16: Swift Examples

  • Page ID
    10635
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    Temperature

    // 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 getFahrenheit() -> Double {
        var fahrenheit: Double
        
        print("Enter Fahrenheit temperature:")
        fahrenheit = Double(readLine(strippingNewline: true)!)!
        
        return fahrenheit
    }
    
    func calculateCelsius(fahrenheit: Double) -> Double {
        var celsius: Double
        
        celsius = (fahrenheit - 32) * 5 / 9
        
        return celsius
    }
    
    func displayResult(fahrenheit: Double, celsius: Double) {
        print(String(fahrenheit) + "° Fahrenheit is " + String(celsius) + "° Celsius")
    }
    
    func main() {
        var fahrenheit: Double
        var celsius: Double
        
        fahrenheit = getFahrenheit()
        celsius = calculateCelsius(fahrenheit:fahrenheit)
        displayResult(fahrenheit:fahrenheit, celsius:celsius)
    }
    
    main()
    

    Output

    Enter Fahrenheit temperature:
     100
    100.0° Fahrenheit is 37.7777777777778° Celsius
    

    References

    • Wikiversity: Computer Programming

    3.16: Swift Examples is shared under a CC BY-SA 4.0 license and was authored, remixed, and/or curated by LibreTexts.

    • Was this article helpful?