Constants in Swift

Go supports constants of character, string, boolean, and numeric values.

const declares a constant value.

import Foundation

let s: String = "constant"

func main() {
    print(s)
    // A const statement can appear anywhere a var statement can.
    let n: Int = 500000000

    // Constant expressions perform arithmetic with
    // arbitrary precision.
    let d: Double = 3e20 / Double(n)
    print(d)

    // A numeric constant has no type until it’s given
    // one, such as by an explicit conversion.
    print(Int64(d))

    // A number can be given a type by using it in a
    // context that requires one, such as a variable
    // assignment or function call. For example, here
    // `sin` expects a `Double`.
    print(sin(Double(n)))
}

main()

To execute this code in a Swift environment, you can use a Swift compiler or any Swift playground. Simply copy-paste the code into the environment and run it.

Here’s the expected output:

constant
6e+11
600000000000
-0.28470407323754404

Now that you understand how constants work in Swift, let’s proceed to more advanced topics.