Introduction To Swift

Payal Kandlur
2 min readMar 22, 2020

Swift is a programming language for iOS, macOS, watchOS and tvOS app development. It adopts the best of C and Objective-C. Like C, Swift provides many variables and constants. Let’s go ahead and explore much of it!

Constants and Variables

You declare a value before you use them (of course). In Swift, constants are declared with a let keyword and variables with the keyword var. Heres how you do it…

let maximumNumberOfLoginAttempts = 10
var currentLoginAttempt = 0

All that you are doing in the above example is declaring a variable named “currentLoginAttempt” and you initialize it to 0. The constant is declared similarly. The only difference between a variable and constant is, your constant value never changes (hence called “constant”). You can declare multiple constants or multiple variables on a single line, separated by commas.

You can also provide type annotations while you declare your constant or variables. This will tell you what is the type your variable or constant is storing.

var variableName:<data type> = <optional initial value>
var welcomeMessage: String
welcomeMessage = "Hello"

Constant and variable names can contain almost any character, including Unicode characters.

let π = 3.14159
let 你好 = "你好世界"
let 🐶🐮 = "dogcow"

NOTE: If you need to give a constant or variable the same name as a reserved Swift keyword, surround the keyword with backticks (`) when using it as a name. However, avoid using keywords as names unless you have absolutely no choice.

How do you print constants and variables?

You can print the current value of a constant or variable with the print(_:separator:terminator:) function:

var greet = "Hi!"
greetAgain = "Hello!"
print(greetAgain)
// Prints "Hello!"

Swift 4 supports the following basic types of variables −

  • Int or UInt − This is used for whole numbers. More specifically, you can use Int32, Int64 to define 32 or 64 bit signed integer, whereas UInt32 or UInt64 to define 32 or 64-bit unsigned integer variables. For example, 42 and -23.
  • Float − This is used to represent a 32-bit floating-point number. It is used to hold numbers with smaller decimal points. For example, 3.14159, 0.1, and -273.158.
  • Double − This is used to represent a 64-bit floating-point number and used when floating-point values must be very large. For example 3.14159, 0.1, and -273.158.
  • Bool − This represents a Boolean value which is either true or false.
  • String − This is an ordered collection of characters. For example, “Hello, World!”
  • Character − This is a single-character string literal. For example, “C”

Swift 4 also allows defining various other types of variables, such as Optional, Array, Dictionaries, Structures, and Classes which we will cover soon!!! 😃

--

--