Fri_Feb__8_12:01:51_PST_2019
Swift - Constants Advertisements Previous Page Next Page ï¿ï¾ Constants refer to fixed values that a program may not alter during its execution. Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal. There are enumeration constants as well. Constants are treated just like regular variables except the fact that their values cannot be modified after their definition. Constants Declaration Before you use constants, you must declare them using let keyword as follows ï¿¢ï¾ï¾' let constantName = Following is a simple example to show how to declare a constant in Swift 4 ï¿¢ï¾ï¾' Live Demo let constA = 42 print(constA) When we run the above program using playground, we get the following result ï¿¢ï¾ï¾' 42 Type Annotations You can provide a type annotation when you declare a constant, to be clear about the kind of values the constant can store. Following is the syntax ï¿¢ï¾ï¾' var constantName: = The following example shows how to declare a constant in Swift 4 using Annotation. Here it is important to note that it is mandatory to provide an initial value while creating a constant ï¿¢ï¾ï¾' Live Demo let constA = 42 print(constA) let constB:Float = 3.14159 print(constB) When we run the above program using playground, we get the following result. 42 3.1415901184082 Naming Constants The name of a constant can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. Upper and lowercase letters are distinct because Swift 4 is a case-sensitive programming language. You can use simple or Unicode characters to name your variables. Following are valid examples ï¿¢ï¾ï¾' Live Demo let _const = "Hello, Swift 4!" print(_const) let ï¿¤ï¾½ï¾ ï¿¥ï¾¥ï¾½ = "ï¿¤ï¾½ï¾ ï¿¥ï¾¥ï¾½ï¿¤ï¾¸ï¾ï¿§ï¾ï¾" print(ï¿¤ï¾½ï¾ ï¿¥ï¾¥ï¾½) When we run the above program using playground, we get the following result ï¿¢ï¾ï¾' Hello, Swift 4! ï¿¤ï¾½ï¾ ï¿¥ï¾¥ï¾½ï¿¤ï¾¸ï¾ï¿§ï¾ï¾ Printing Constants You can print the current value of a constant or variable using print function. You can interpolate a variable value by wrapping the name in parentheses and escape it with a backslash before the opening parenthesis: Following are valid examples ï¿¢ï¾ï¾' Live Demo let constA = "Godzilla" let constB = 1000.00 print("Value of \(constA) is more than \(constB) millions") When we run the above program using playground, we get the following result ï¿¢ï¾ï¾' Value of Godzilla is more than 1000.0 millions Previous Page Print Next Page ï¿ï¾ Advertisements
Comments
Post a Comment