Tuesday, February 13, 2018

Swift 4 Introduction Series 1.2 - Swift Variables & Constant

Swift Variables

Similar to other programming language, Swift also use constant and variables. Constant is a name/labeled use to reference selected data that will not change. Constant can only be declared and assigned once. It cannot be redeclared or reassigned in the same program. But we can refer to constant many times. Variables is a name/labeled use to reference selected data that may change. We can reassign other data to the variable as long as the reassigned data is of the same datatype as it is declared. Variables can only be declared once in a program. It cannot be redeclared in the same program.

Introducing Swift Basic Data Type

The 3 basic data type for Swift are String for text, Int for integers and Double for floating point number. Swift encourage us to use the above basic data type for better interoperability.

In addition, we have UInt for unsigned integer and Float for smaller floating point number. UInt and Float should only be used when necessary.


In addition to String, we also have data type known as Character. This is a data type that holds a single character.

Finally we have Bool for boolean values which store only True or False.

Constant

We declared constant using the following syntax:

let <constant_name> = <data/expression that derived into data>

Basic rules for Constant:
  • A constant MUST be declared before use.
  • A constant can only be declared ONCE. Once a constant has been declared, the constant with the same name cannot be redeclared again in the same program.
  • A constant can only be assigned ONCE. Once a constant has been assigned, it cannot be reassigned with other data.
  • Naming of the constant must follow the naming rules.

In Swift, we are encouraged to use constant as  much as possible. This is to make the code safer.

Example:

let someString = "This is a test"

let someNumber = 18273

Screen Shot 2017-11-02 at 20.39.41.png




In the example above, we do not need to define the data type when we declare constant with the value. The system will infer the data type from the value we supply.

We can declare multiple variable with multiple data type in a single statement by using comma to separate the variables. However, constant and variable cannot be used in the same statement.

Example:

let fixed1 = 2837, fixed2 = 7238, fixed3 = 8320

fixed1
fixed2
fixed3

Screen Shot 2017-11-02 at 20.43.25.png
Example:

let c1 = 10, c2 = true, c3 = 1.2, c4 = "Constant String"

c1
c2
c3
c4

Screen Shot 2017-11-02 at 20.46.04.png

Variables

We declared variables using the following syntax:

var <variable_name> = <data/expression that derived into data>

Basic rules for Variable:
  • A variable MUST be declared before use.
  • A variable can only be declared ONCE. Once a variable has been declared, the variable with the same name cannot be redeclared again in the same program.
  • However, we can reassigned other data of the same type to the same variable many times.
  • Naming of the variable must follow the naming rules.

Example:


var someVariableString = "Default String"

var someVariableNumber = 387482

someVariableString = "Default string changed"

someVariableNumber = 263545674
 


Similar to constant, we also do not need to declare the data type when we declared variable with an initialized value as the system will infer the data type from the initialized value.

We can also declare multiple variable with multiple data type using comma. However, constant and variable cannot be used in the same statement.

Example:

var x = 12, y = 23, z = 93

x
y
z

x = 24
y = 54
z = 33




Example:

//: We can also declare multiple variable in a single statement, use comma to separate the variables. Please note that constant and variable cannot be used in the same statement.
var v1 = 1024, v2 = 1.4, v3 = false, v4 = "Mutable String"

v1
v2
v3
v4


Naming Constants and Variables

The are some basic rules in naming constant and variables
  • Constant or variables name must be in a block of words with no space in between. We can use underscore (_) to join two words into a constant or variable name.
  • It cannot begin with a number. Number can be added from the second character onwards.
  • It cannot contain special character or mathematical symbol except _ and $. However, we cannot use $ as the first character for constant or variables.
  • We may use underscore (_) as the first character of constant or variable. However it is not encouraged.
  • We cannot use Swift reserved keyword as constant or variable name. Although work around is available, please refrain from doing so unless there is no other choice.
  • We can use other unicode character as the name as long as the unicode character is not classified as arrow, line-drawing character or box-drawing character. Only some symbol can be used as name.

Example:

The following examples are acceptable constant/variable name:

let sample1 = 823, SAMPLE2=76, sample$ = 21

let s12constant = 34, S11 = 65

let more_example = "Test", _name = "should not use this"

let ᗘ = 12, ្ = 23, ᴔ = 3, ① = "this"

let Ω = 88, Π = 3.1415




Additional Example:

let 🤔 = 98

let 🤓 = "emoji can be accepted"

let ゆ = "Japanese Character"

let 中文 = "Chinese"

let 🇨🇭 = "Swiss Flag"

Second Screenshot




Some more example:

//: Swift also supports unicode and multiple languages
let 😀 = "Happy"
var seeYouSoon = "À_bientôt"
let どうぞ = "Dozo"
let time = "時間"
var 你好世界 = "Hello World"
let π​ = 3.14159
let 五 = 5
let nine = "九"




Note:
  • Not everything inside the Unicode is acceptable as constant/variable name.
  • Some symbol such as omega is actually latin character, therefore it is acceptable as name.
  • Emoji and flag are symbols that is acceptable as name.
  • All other languages are acceptable as name as shown above.
  • Although some of the name in the example is acceptable as  a constant/variable name. However, it may not be conform to the acceptable convention.



Below are the basic convention that we are recommended to use. It will not generate error if we do not follow the recommended convention however it will lead to confusion and miscommunication when we share code with others.


  • Although we can use underscore as the first character for constant or variable name, please refrain from doing so because it has a special purpose.
  • Please do not use capital letters as the first character for constant and variables. It is reserved to describe data type such as Int and Double.
  • Please use capital letter from second word when joining multiple word together. Such as exampleOfVariableName.

Recommended convention for constant and variable is as follows:

  • Start with small letter
  • Use capital for subsequent words

Example:

let sampleWord = "Test"

let sampleNumber = 76

let thisIsATestConstantName = 54




Data Type Inference
We do not need to specify the data type when we declared and assign constant or variables at the same time. The system will examine the data and decide the data type for us. This process is called Data Type Inference.

How to know if a constant or variable belongs to which data type? We can do so in Xcode by hovering the cursor to a variable while holding the option key. A question mark icon will hover over the constant or variable. Then we need to click on the question mark. See screenshots below.





Swift can only infer the following data types, they are String, Int, Double and Bool. If we need to use any other data type, we must include data type annotation.

For expression or computation, the system will infer to the most appropriate data type base on the evaluation of expression. If we add multiple string together, the system will infer the constant as string as shown below:

Example:


let someConstant1 = "Hello!" + " " + "How are you?"



For integer computation, the system will inferred the constant as Integer.

Example:

let someConstant2 = 3 + 10



Similarly, floating point computation will infer to Double.

Example:

let someConstant3 = 3.1415 + 2.7815



However, if we are to mixed the data, the system will inferred the constant to the most appropriate data type.

Example:

let someConstant4 = 3 + 0.1415



In the example above, the expression is the computation with an integer and floating point number. In such cases, the system will infer the constant to a floating point data type.

Data Type Annotation
In some situation where we need to declare a constant or variable but we do not have the data yet. Then we need to use data type annotation to declare a constant or variable.

We also need data type annotation for any data type that Swift cannot infer such as UInt or Float.

Declare Constant or Variable Without Data
To declare a constant without data, use the following syntax:

let <constant_name>:<datatype>

We can also declared variable without data as shown in syntax below, however, Swift recommend the safer way to create variable output data.  

var <variable_name>:<datatype>

The safer method to create variable without data

var <variable_name> = <datatype>()

The above syntax create variable and initialized the variable at the same time.

Example:

let someOtherString:String

var someOtherVariableNumberNotSafe : Int

var someOtherVariableNumberSafer = Int()




In the above example, we created a constant and a variable. Please note that whitespace is not required for the colon (:) sign.

To assign values to the constant and variable:

let someOtherString:String

var someOtherVariableNumber : Int

someOtherString = "This string cannot be changed anymore once it is assigned."

someOtherVariableNumber = 23

someOtherVariableNumber = 100




For constant, we can only assign the data ONCE. After that we cannot reassign the data again. On the other hand, we can reassign the variable with different data value as long as the data type is integer.

Similarly, we can declare multiple constant or variable in a statement by indicating the datatype for the last variables.


var sample1, sample2, sample3:UInt

let sample4:Float, sample5:String, sample6:Int




Note:
  • In the example above, sample1, sample2 and sample3 are of the same data type


Important Note:
Although we can declared constant or variable without assigning data. This is not a recommended practice as it may make our code unsafe when we forget to assign data to the declared variable. For declaring constant, we should assigned the value during declaring. We should use the method above only when absolutely necessary. For variables, we can declared them and initialized the variables at the same time without assigning data.

The following example repeats the previous example but we initialise the variable without assigning data.

Example:


//var someOtherVariableNumber : Int
var someOtherVariableNumber = Int()
someOtherVariableNumber




The example above is the recommended practice when we need to declare variable but we do not need to assign any data to it yet.


In the following example, we declare the variable by indicating the data type. At the same time we also supply its initial value. Such statement is unnecessary since the data can perform data type inference although it is acceptable by the system.

Example:


// The following statement is acceptable although including the datatype is not necessary.
let someConstant3: Int = 1000
var someString3: String = "Another mutable string"




Declaring Constant and Variable for Other Data Type

As a reminder, Swift only able to infer Int, String, Bool and Double. In the following example, we must include data type because Swift cannot infer data type such as Float, UInt, Int32 etc.


Example:


// In the following example, we must use data type annotation because Swift cannot infer such data type

let someFloat:Float = 25.36

let someUnsignedInteger:UInt = 2656

let someBitSizeInteger:Int32 = 5646532




Other Uses for Type Annotation

In certain situation where the name of the variable or constant is using similar data type, we can avoid confusing by adding type annotation during data declaration. This will helps programmer to avoid mistake during data declaration.

For example, it can be confusing to determine or distinguish between integer and floating point number.



In the example above, the first number is integer whereas the second number is a floating point number. For the second number, if we forget to put 0.0 and enter 0 instead; then the data type will be inferred as integer. To ensure that what we declare is a floating point number, we can add type annotation like the third number. Therefore, we recommended that when we need to initialize a variable to zero, it is the best to include data type in order to avoid mistake like forgetting to enter 0.0 instead of 0.

In another situation where the name of variable or constant is quite similar. Declaring them with data type annotation helps to distinguishing between different variables with similar name.



In the previous example, the two variable names is quite similar. What happen if we make a mistake as follows:



In the previous example, there will be no error even if we make a mistake. If we declare with data type annotation, the result will show us an error.




Print Constant and Variable

To print constant or variable, we just need to place the constant or variable within the parenthesis.


Example:


let someText = "This text is fixed."

var someNumber = 986

print(someText)

print(someNumber)

someNumber = 123

print(someNumber)






To print multiple variables, we can insert a comma between variables


Example:


let someText = "This text is fixed."

var someNumber = 986

print(someText, someNumber)

someNumber = 123

let anotherNumber = 374

print(someNumber, anotherNumber)






We can print multiple string into a statement.


Example:


let someText = "This is some text"
let someText2 = ". This is second sentence to be joined with the first"
let someText3 = ". Third sentence."

// The follow print statement could not join 2 variables
print(someText)
print(someText2)

// The following print statement can join 3 string with a space between variables
print(someText, someText2, someText3)


Screen Shot 2017-11-03 at 20.47.53.png


String Interpolation

What happen if we want to print some string literal together with variable in order to explain the data? Print function use string interpolation. To do that we need to enclosed the constant or variable with \(constant_or_variable).


Example:


let revenue = 143000
print("The revenue for this season is US$\(revenue). This is a good season.")






Print Function

The Print function is actually denoted as print(_:separator:terminator:). The first parameter is the print item. It could be a string literal, numeric literal, constant or variables.


The second parameter is separator for multiple item. The default is a single space. If we would like to change the separator, we can change it using the parameter.


The following example shows printing multiple item using default separator:


Example:


print(1,2,3,4,5)




The following example shows printing multiple items using custom separator "=>"


print(1,2,3,4,5, separator:"=>")




The third parameter is the terminator. The print function will include a new line (\n) as the terminator by default. This means that the print print statement will start on a new line. However, if we want to print the second variable immediately after the first variable without a line break, we can change the terminator to "". Please see example below.


Example:


let prnMessage1 = "This is a sample message."
let prnMessage2 = "This is 2nd message."

print(prnMessage1, terminator: "")
print(prnMessage2)



*** End ***