You’re 7 mins away from Swift 4

Yogesh Manghnani
codeburst
Published in
7 min readMar 31, 2018

--

Swift is a general purpose, strictly typed programming language developed by Apple in 2014. It is used widely for development in the Apple ecosystem. Which include iOS, macOS, tvOS and watchOS. If you are looking for a quick start guide for Swift 4 you are in reading the best possible article.

Data Types available in Swift 4

  1. Int
  2. Double
  3. Float
  4. Bool
  5. String
  6. Array (collection type)
  7. Set (collection type)
  8. Dictionary (collection type)

Variables

Variables are containers in which data can be stored. This data can be of different types more about that in a later section. This variables can be manipulated and mutated whenever needed. The data can also be called values of the variables. Variables can be assigned new values. They can also be mutated and played around with.

var number = 100              //This is a Int
var float = 100.20 //This is Float
var string = "Hello everyone" //This is a String
var anotherFloat:Double = 100 // This is Float

Note:- Though Swift is strictly typed. It can infer data types on its own.
One can use a (:) to explicitly state the data type

Constants

Constants are also containers for storing data. But these constants cannot be manipulated and changed. As the name implies they are constants.

let constant  = 10
let doubleConst = 10.908
let stringConst = "This is a String"

Collection Types

A collection is a collection of variables. There are three types of collections in Swift. These collections are Arrays, Sets, Dictionaries.

Arrays are collections in which every value has an index. These values can be accessed using their indexes.
Sets are collection types with special feature that only one instance of a particular value can exist in a set. (There can not be more than one ‘2’ in a Set of Integers
Dictionaries are hash tables of Swift. The store key value pairs.

let array = [10, 17, 18, 99]
let set : Set<Int> = [10, 17, 99]
let dictionary = [1: "hello", 9: "200"]

Loops

Loops are used when you want to repeat some code again and again.

You use the for-in loop to iterate over a sequence, such as items in an array, ranges of numbers, or characters in a string. This example uses a for-in loop to iterate over the items in an array:

let names = ["John", "James", "Jason", "Jonny"]
for name in names {
print("\(name)")
}
//John
//James
//Jason
//Jonny

A while loop starts by evaluating a single condition. If the condition is true, a set of statements is repeated until the condition becomes false.

while condition {
statements
}

The other variation of the while loop, known as the repeat-while loop, performs a single pass through the loop block first, before considering the loop’s condition. It then continues to repeat the loop until the condition is false.

repeat {
statements
} while condition

Conditional Statements

In its simplest form, the if statement has a single if condition. It executes a set of statements only if that condition is true.

if condition {
statement
}

You can chain multiple if statements together to consider additional clauses.

if condition {
statements
} else if condition {
statements
} else {
statements
}
A switch

A switch statement considers a value and compares it against several possible matching patterns. It then executes an appropriate block of code, based on the first pattern that matches successfully. A switchstatement provides an alternative to the if statement for responding to multiple potential states.

switch someVariable {
case value1:
response
case value2:
response
default:
response
}

Functions

Functions are self-contained chunks of code that perform a specific task. You 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.

Functions can be thought of a person whom you call and give him your stuff. This great person will process your stuff and then return you the the product of all the processing. This is a great way for abstraction of your code. This also makes your code more efficient.

func printMsg(nameOfPerson: String){
print("Hello \(nameOfPerson)")
}
//This function does not return. It only does some workfunc square(number: Int) -> Int {
return number*number
}
//The above function returns a value

Object Oriented Programming

Classes in Swift

Classes in Swift can just be declared as below

class className {
var one
var two
var three

func someFunc(someArgument:String){
//Code
}
}

Classes are used for various reasons. They provide a better code structure and a great way to encapsulate the data. Classes also provide inheritence. Classes help the user to build multiple objects. Every objects has some properties and some methods that can be used to manipulate its properties. These objects are passed around by reference and not by copying. In case you want to pass things around by copying you can use structures.

Structures

Structures are used to create heterogeneous collection of variables. These are great and efficient for storing data. One should always use a structure when any specific feature of classes is not required. Structures are great for various reasons like - it is easier to pass around without thinking about pointers and other things.

struct StructureName {
var one
var two
//Some functions here
}

Identity Operators

Because classes are reference types, it is possible for multiple constants and variables to refer to the same single instance of a class behind the scenes. (The same is not true for structures and enumerations, because they are always copied when they are assigned to a constant or variable, or passed to a function.)

It can sometimes be useful to find out if two constants or variables refer to exactly the same instance of a class. To enable this, Swift provides two identity operators:

  • Identical to (===)
  • Not identical to (!==)

There are many more things in Swift which include protocols, extensions. Before reading forward make sure that you have read and understood all the above completely.

Protocols

A protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality. The protocol can then be adopted by a class, structure, or enumeration to provide an actual implementation of those requirements. Any type that satisfies the requirements of a protocol is said to conform to that protocol.

protocol protocolName {
var name1
var name2
}

These protocols can be accepted by classes as below

class someClass: protocolName {
var name1
var name2
}

There are many predefined protocols made by Apple that can be used very effectively. More about that for some other post.

Extensions

Extensions add new functionality to an existing class, structure, enumeration, or protocol type. This includes the ability to extend types for which you do not have access to the original source code (known as retroactive modeling). Extensions are similar to categories in Objective-C. (Unlike Objective-C categories, Swift extensions do not have names.)

Extensions in Swift can:

  • Add computed instance properties and computed type properties
  • Define instance methods and type methods
  • Provide new initialisers
  • Define subscripts
  • Define and use new nested types
  • Make an existing type conform to a protocol
extension Int{    var arc4random : Int {        if self > 0 {            return Int(arc4random_uniform(UInt32(self)))        } else if self < 0 {            return -Int(arc4random_uniform(UInt32(abs(self))))        } else {            return 0        }    }}

Enumerations

An enumeration defines a common type for a group of related values and enables you to work with those values in a type-safe way within your code.

If you are familiar with C, you will know that C enumerations assign related names to a set of integer values. Enumerations in Swift are much more flexible, and do not have to provide a value for each case of the enumeration. If a value (known as a “raw” value) is provided for each enumeration case, the value can be a string, a character, or a value of any integer or floating-point type.

Alternatively, enumeration cases can specify associated values of any type to be stored along with each different case value, much as unions or variants do in other languages. You can define a common set of related cases as part of one enumeration, each of which has a different set of values of appropriate types associated with it.

Enumerations in Swift are first-class types in their own right. They adopt many features traditionally supported only by classes, such as computed properties to provide additional information about the enumeration’s current value, and instance methods to provide functionality related to the values the enumeration represents. Enumerations can also define initializers to provide an initial case value; can be extended to expand their functionality beyond their original implementation; and can conform to protocols to provide standard functionality.

enum compassPoint {
case north
case south
case west
case east
}
let direction = compassPoint.west

That’s it for this article. More about each topic will be coming soon.

Follow me on Instagram
Follow me on Twitter
Follow me on WordPress

✉️ Subscribe to CodeBurst’s once-weekly Email Blast, 🐦 Follow CodeBurst on Twitter, view 🗺️ The 2018 Web Developer Roadmap, and 🕸️ Learn Full Stack Web Development.

--

--

I am fullstack developer who can’t sleep with bugs. (both in bed and in code)