Saturday, April 22, 2017

Book I Chapter 1: Swift Basics

Chapter 1: Swift Basics



Introducing Swift Features

Swift programming adopt the useful features from Objective-C and remove all the unnecessary syntax which is inherited from the C programming language. First, we do not need to use semicolon to end the instruction, although we still use curly braces to group instructions. There will be no integer overflow, thus reduce the risk of error. Swift also save us from declaring data type when the system can infer the data type from the data we supply.


Swift also implement traditional method of control flow in a safer way. For example, in C programming we can use 0 as an alternative for false. In Swift, while we evaluating conditional statement, we must provide expression that will evaluate to boolean value. Swift also implement switch statement in a safer manner. There will be no fall through in switch statement. This is to eliminate unintentional mistake.


Swift Basic Syntax

The following is the basic syntax of Swift:
  • Swift is case sensitive
  • There must be a minimum of ONE whitespace before and after each token. Additional whitespace will be ignore. Some symbol such as arithmetic symbol like +,-,*,/,% and :, (), [] or {} does not require any whitespace before or after the symbol. We can add space to improve readability.
  • Swift will ignore any text that marked as comment.
  • The system will accept an instruction per line. For multiple instruction on a single line, a semicolon is required.
  • Instructions can be grouped together using curly braces.


Comment

Similar to some other programming language, comment is denote by // for single line comment. For multiple line comment, the comment must be enclosed by /* and */.


For multiple line comment we can use multiple comment marker in a nested form as long as the marker are enclosed in a proper order. See example below.
Example:


Please note that for the first line, we have a single line comment follow by a colon. This is a special markup formatting for Playground. It will convert the comment into a more readable text format.


For nested comment, we can have many nested comment as long as the comment marker are enclosed in an orderly fashion.


Example:


/* First level
/* Second level
/* Third level
/* Fourth level
Multi line comment
*/
Addition multi line comment for third level
*/
Additional comment for second level
*/
Comment for first level
*/


Multiple Instruction in a Line

As mentioned in the basic syntax, Swift only accept one instruction per line. If we were to include 2 instructions in a line, we need to add semicolon (;) between instructions.


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 re-assigned in the same program. But we can reference 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 data type 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.


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.


Example:



let someString = "This is a test"

let someNumber = 18273



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 





Example:



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

c1
c2
c3 
c4




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 joint 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.


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 or variable without data, use the following syntax:


let <constant_name>:<datatype>


Or


var <variable_name>:<datatype>


Example:

let someOtherString:String

var someOtherVariableNumber : 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:

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


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 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

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 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.




Printing in Swift

Swift support printing by using the function print(...). We can use print function to print literal text and number. We can also print the value of constant or variable we use.


Print Literal Text and Number



Print Literal Text

To print text using print function please use the following syntax:


print("<Enter text here>")


Example:



print("")

print("This is a test")




Note:
  • Please note that to print literal text we must enclose the text with double quotation in the parenthesis.


We can print almost all the special character except double quotation " and backslash \.


Example:


print("~!@#$%^&*()_+`-={}[]|:;'<>,.?/")






To print quotes, we can use single quotation mark as shown in the following example:



print("He said:'This food is good for you!' and I agree.")






However, if there is a need to use double quotation in the print function, we can use the backslash \ as an escape sequence. In the print function, escape sequence will be noted and the system will force print the next character after the escape sequence.


To print double quotation, we need to use \" instead of ". To print backslash, we need to use \\ instead of \. The print function will noted the first escape sequence but it will not print the escape sequence. See example below:



print("He said:\"This food is good for you!\" and I agree.")

print("To print double quotation in print function, we must use escape sequence \\ to force print \\ and \". ")






Note: there is no typo, please refer to the printed statement.

Print Literal Number

To print number, please follow the syntax below:


print(<Enter number here>)


Example:



print(5246)

print(-587)

print(3.1415)




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)






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.")




**** End of Chapter ****