What is Swift?
Swift is a general-purpose, multi-paradigm programming language developed by Apple Corporation for the products catering to its ecosystem. These include iOS, macOS, Linux, and z/OS platforms. It is designed to run along Apple’s Cocoa and Cocoa Touch frameworks, and the large body of existing Objective-C code written for Apple products.
It is built using the open-source LLVM compiler framework and has been included in Xcode since version 6. It utilizes the Objective-C runtime library which allows C, C++, Objective-C, and Swift code to run within one program.
Swift is exceptionally safe, and interactive and combines the best in modern language thinking, with wisdom from the broader Apple engineering culture and copious contributions from its open-source community.
If you wish to venture into the domain of App Development, then these series of posts could serve as a holy grail for you.
Here’s our guide for beginners to learn Swift. Go through it sincerely, and by the end of it, you’ll acquire a clear and comprehensive understanding of the concepts of Swift 101.
- Variable and constant
In the entire project life cycle, we need to stock a lot of information. Some data needs to be altered while sometimes it needs to be as is. To achieve this, we have Variables & Constants.
- A variable is a designated memory location which temporarily stores data and can acquire different values while the program is running. One can declare a variable by using the ‘var’ keyword.
- A constant is a designated memory location that briefly stores data and remains the same throughout the execution of the program. If you want to retain a particular value – declare them as constant.If you try and change the value of constant, Xcode will show an error message and won’t proceed further. This helps in code optimization and makes your code run faster.Constant in Swift is declared by using ‘let’ keyword, as was applied in elementary Mathematics.
NOTE: It is important to note that we must ALWAYS assign a unique name for constants and variables to avoid a compilation error.
- Data Types
We have different classifications of data in general, like name, phone number, weight, etc. Now how to represent them in a project using the language of computers?
Here comes into play – Data types. In computer science, including computer programming, a data type or simply type is an attribute of data which tells the compiler and the interpreter how the programmer intends to utilize the data.
i) String: As the name suggests, we can store a sequence of characters in this data type.
For example :
- Any entity: “Engineerbabu”, “India”, etc.
- Any sentence: “How are you?” , “This is a really nice blog.”
Syntax: import UIKit let constant : String = "Mitesh" print (constant)
ii) Int: Int is used to store the whole number, where Int32, Int64 is used to store 32 or 64 bit signed integer and UInt32, UInt64 is used to store bit unsigned integer
For example: Any whole numeric number: 42, 100, 999
Syntax: var int = 42 print (int)
iii) Float: This data type is applied to store a 32-Bit floating point number. They are used to store the fractional component.
For example: Any fractional value: 1.343555
Syntax: var float = 1.343555 print(float)
(iv) Double: This data type is employed to store 64-bit Floating point number. They are also employed to store the fractional component. Double has better accuracy than float.
Any fractional value: 1.34315
Syntax: var double = 1.24315 print (double)
v) Bool: Bool stores a Boolean value which can either be true or false. Use this when you require a firm outcome.
For example:
- Do you want to receive push notifications?
- Do you want to allow the user to see your mobile number?
Syntax: var boolVariable = false boolVariable = true
Here are the limits of the data type.
Type | Typical Bit Width | Typical Range |
Int8 | 1byte | -127 to 127 |
UInt8 | 1byte | 0 to 255 |
Int32 | 4bytes | -2147483648 to 2147483647 |
UInt32 | 4bytes | 0 to 4294967295 |
Int64 | 8bytes | -9223372036854775808 to 9223372036854775807 |
UInt64 | 8bytes | 0 to 18446744073709551615 |
Float | 4bytes | 1.2E-38 to 3.4E+38 (~6 digits) |
Double | 8bytes | 2.3E-308 to 1.7E+308 (~15 digits) |
iv) Dictionary: Dictionary is employed to store an unsorted list of values of the same Swift 4 puts strict checking which does not allow you to enter a wrong type in a dictionary even by error.
v) Array: Arrays are used to store lists of values of similar type. Swift 4 puts strict checking which does not allow you to enter a wrong type in an array, even by mistake. All the objects of an array ought to be of the same data type, i.e., int string, dictionary, double, etc.
- Conditional statements
Sometimes we wish to execute code if a specific condition is valid. It is represented primarily by the if and else statements. You give Swift a condition to check, then a block of code to execute if that condition is found true.
- Loop
When it comes to performing a repetitive task, it is not feasible to type the same code again and again; instead, one can use loops. Loops are simple programming constructs that repeat a block of code for as long as a condition is deemed true.
Example: a) For loop for i in0..<5 { print(i) } b) While loop var index =10 while index <20{ print("Value of index is \(index)") index = index +1 }
- Function
Functions are self-contained blocks of code that perform a specific task. You can give a function a name that identifies what it does, and this name is used to call the function to perform its task when needed. Every function in Swift has a particular type, consisting of the function’s parameter type and return type.
Example:
a) Function definition without parameter and return type: This method is not taking any parameter and returning value that needs to be handled.
func student()->String{
return"Ram"
}
b) Function definition with parameter and return type: This is an example of a method taking a string parameter and returning received a string that needs to be handled from where it is called.
func student(name:String)->String{
return name
}
c) Function call without parameter and a returned value
student()
d) A function call with parameter and return value
print(student(name:"Mohan"))
- Optional
The optional type in Swift 4 handles the absence of a value. Optional means either “there is a value, and it equals some value like “X” or “there isn’t a value at all.”
var string: String?=Nil if string !=nil{ print(string) }else{ print("string has nil value") }
Forced Unwrapping
If you defined a variable as optional, then to acquire value from this variable, you need to unwrap it. This is achieved by placing an exclamation mark at the end of the variable.
var string: String? string ="Hello!" if string !=nil{ print(string) // Optional("Hello!") }else{ print("string has nil value") }
Now apply unwrapping to get the correct value of the variable
var string: String? string ="Hello" if string !=nil{ print(string!) // "Hello!" }else{ print("string has nil value") }
- Enumeration
It is an user-defined data type which consists of a set of related values. “enum”Keyword is used to defined enumerated data type. Enum is declared in the class, and it can be accessed throughout the instance of the class. Initial member value is defined using enum initializers, and functionality is also extended by ensuring standard protocol functionality
Example with type: enum GenderType : String{ Case Male Case Female } Switch Statement using enums: var gender = GenderType.Male switch gender { case .Male: case .Female: }
- Struct
Structs are basic constructs of a program. In Swift, structs can have properties and functions. The key difference is that structs are value types and classes are reference types. Because of this, let and var behave differently with structs and classes.
structPerson { var name:String var gender:String var age:Int init(name: String, gender: String, age: Int) { self.name = name self.gender=gender self.age = age } } let person1 =Dog(name: "Mohit", gender: "male", age: 14) var person2 =Dog(name: "Ram", gender: "male", age: 25) person2.name ="Lucy"
- Class
Classes are the building blocks of flexible constructs and are similar to constants, variables, and functions users use to define class properties and methods. Swift 4 gives us the functionality that while we declaring classes the users need not create interfaces or implementation files which we need to do with Objective C. Swift 4 allows us to create classes as a single file and the external interfaces will be created by default once the classes are initialized.
What are the benefits of having Classes–
- Inheritance
- Typecasting
- Automatic reference counting
There are specific characteristics which are similar to structures
- Properties are defined to store the values
- Subscripts are defined for providing access to values
- Methods are initialized to improve functionality
- Functionality is expanded beyond default values
Example: class student { var studname: String var mark: Int var mark2: Int }
Wrapping up…
I hope you enjoyed reading this brief Swift Tutorial. Start practicing on these basics right away, we’ll be creating many more posts for you to clearly comprehend the basics of Swift.
This is just the tip of the iceberg when you consider the vastness of this domain. We’ll be furthering covering various aspect of Swift Programming in the upcoming series of articles. So, stay tuned!