The Basics Of Swift

Manish Ahire
6 min readMay 26, 2018

--

Swift is a new programming language for iOS, macOS, watchOS and tvOS app development. Many parts of the swift will be familiar with C and Objective C.

Swift provides its own version of all fundamental C and Objective C types, including Int, Double, Float, Boolean and String. Swift also provides a collection of types of Array, Set, and Dictionary.

Swift introduces advanced type not found in Objective C, such as Tuples. Tuples enable you to create and pass around a grouping of values.

Constants and Variables

Constants and variables associate a name with a value of a particular type. You declare constants with the let keyword and variables with the var keyword.

let a = 10
var b = 20
var x = 10, y = 20, z = 30

You can provide a type annotation when you declare a constant or variable to be clear about the kind of values the constant or variable can store.

var name : String
var a, b, c : Double

Comments

Comments in swift are very similar to comments in C.

// This is a comment./* This is also comment
but it is written over multiple lines */
/* This is the start of the first multiline comment.
/* This is the second, nested multiline comment. /*
This is the end of the first multiline comment. /*

Semicolons

Semicolons are required if you want to write multiple separate statements on a single line.

let a = 10; print(a)
// Prints 10

Integers

Swift provides signed and unsigned integers in 8, 16, 32 and 64 bits forms.

Integer Bounds: You can access the minimum and maximum values of each integer type with its minimum and maximum properties.

let minValue = UInt8.min // minValue is equal to 0, and is of type UInt8.let maxValue = UInt8.max // maxValue is equal to 255, and is of type UInt8.

Int: In most cases, you don’t need to pick a specific size of integer to use in your code. Swift provides an additional integer type Int which has the same size as the current platform’s native word size.

On a 32-bit platform, Int is the same size as Int32.
On a 64-bit platform, Int is the same size as Int64.

UInt: Swift also provides an unsigned integer type UInt which has the same size as the current platform’s native word size.

On a 32-bit platform, UInt is the same size as UInt32.
On a 64-bit platform, UInt is the same size as UInt64.

Floating-Point Numbers

Floating-Point types can represent a much wider range of values than integer types and can store numbers that are much larger or smaller that can be stored in an Int. Swift provides two signed floating-point number types :
1. Double represents a 64-bit floating-point number.
2. Float represents a 32-bit floating-point number.

Numeric Literals

Integer literals can be written as:
1. A decimal number, with no prefix.
2. A binary number, with a 0b prefix.
3. An octal number, with a 0o prefix.
4. A hexadecimal number, with a 0x prefix.
All of these integer literals have a decimal value of 17:


1. let decimalInt = 17
2. let binaryInt = 0b10001 // 17 in binary notation
3. let octalInt = 0o21 // 17 in octal notation
4. let hexadecimalInt = 0x11 // 17 in hexadecimal notation

Type Aliases

Type aliases define an alternative name for an exiting type. You define type aliases with typealias keyword.

typealias aInt = UInt16

Once you define a type alias, you can use the alias anywhere you might use the original name.

var bInt = a.min
// bInt is now 0

Booleans

Swift has a basic boolean type called Bool. Boolean values are referred to as logical because they can only ever be true or false. Swift provides two Boolean constant values, true and false:

let a = true
let b = false

Tuples

Tuples groups multiple values into a single compound value. The values within tuples can be of any type and do not have to be of the same type as each other.

let httpError = (404, “Not Found”)

You can create tuples from any permutation of type and they can contain as many different types as you like. There’s nothing stopping you from having a tuple of the (Int, Int, Int) or (String, Bool).
You can decompose the contents of a tuple into separate constants or variables, which you then access as usual:

let (code, error) = httpError
print(code) // code is 404
print(error) // error is Not Found

If you only need some of the tuple’s values, ignore parts of the tuple with an underscore ( _ ) when you decompose the tuple:

let (code, _ ) = httpError
print(code) // code is 404

Alternatively, access the individual element values in a tuple using index numbers starting at zero:

print(“The status code is \(httpError.0)”)
// The status code is 404.
print(“The status message is \(httpError.1)”)
// The status message is Not Found.

You can name the individual elements in a tuple when the tuple is defined:

let httpError = (statusCode : 404, description: “Not Found”)

You can use the element names to access the values of those elements:

print(“The status code is \(httpError.statusCode)”)
// The status code is 404.
print(“The status message is \(httpError.description)”)
// The status message is Not Found.

Tuples are particularly useful as the return values of functions. By returning a tuple with two distinct values, each of a different type, the function provides more useful information about its outcome than if it could only return a single value of a single type.

Optionals

You use optional in situations where a value may be absent. An optional represent two possibilities: Either there is a value or there is not a value at all.

let strRollNo = “123”
let intRollNo = Int(strRollNo)
// intRollNo is inferred to be of type “Int?”, or “optional Int”

An optional Int is written as Int? not Int. The question mark indicates that the value it contains is optional, meaning that it contains some Int value, or it might contain no value at all.

Nil: You set an optional variable to a value less state by assigning it the special value nil.

var a : Int? = 101
a= nil // a now contains no value

You can use an if statement to find out whether an optional contains a value by comparing the optional against nil.

if a != nil {
print(“a contains some integer value”)
}
// Prints a contains some integer value

Forced Unwrapping: Once you’re sure that the optional does contain a value, you can access its underlying value by adding an exclamation mark (!) to the end of the optional’s name. The exclamation mark effectively says, “I know that this optional definitely has a value; please use it.” This is known as the forced unwrapping of the optional value:

if a != nil {
print(“a has an integer value of \(a!)”)
}
// Prints “a has an inter value of 101”

Optional Binding: You use optional binding to find out whether an optional contains a value, and if so, to make that value available as a temporary constant or variable. Optional binding can be used with if and while statements to check for a value inside an optional, and to extract that value into a constant or variable, as part of a single action

if let rollNo = Int(strRollNo) {
print(“Actual No : \(rollNo)”)
} else {
print(“strRollNo could not be converted to an integer”)
}
// Prints Actual No is 101

Implicitly Unwrapped Optionals: Sometimes it is clear from programs structure that an optional will always have a value.
These, kinds of optional are defined as implicitly unwrapped optional. You write an implicitly unwrapped optional by placing an exclamation mark (!) rather than a question mark (?).

let strFirst : String? = “ABCD”
let strSecond : String = strFirst! // requires an exclamation mark
let strName : String! = “ABCD”
let strName1 : String = strName // no need for an exclamation mark

Error Handling

You use error handling to respond to error conditions your program may encounter during execution.
When a function encounters an error condition, it throws an error. That function’s caller can then catch the error and respond appropriately.

func canThrowAnError() throws {
// this function may or may not throw an error
}

When you call a function that can throw an error, you prepend the try keyword to the expression.

do {
try canThrowAnError()
// no error was thrown
} catch {
// as error was thrown
}

--

--

Manish Ahire

Helping developers to understand technology simply. About me: manishahire.com and My blog: mobodevstuff.com