Job-ready Online Courses: Click for Success - Start Now!
Swift – a modern and powerful language. It’s used to build applications for iOS, macOS, TvOS, and watchOS platforms. Swift is popular for its straightforward and expressive syntax. In this article, we’ll be diving into the basic syntax of Swift. We’ll cover essential concepts like comments, semicolons, tokens, whitespaces, imports, and many more.
Let’s begin with our first program to get a glimpse of the syntax of Swift.
print("Hello from DataFlair!")
Output:
Hello from DataFlair!
Comments
Comments are like the helping texts in our programs, which the compiler ignores. They are essential to add explanations and notes within our code. Swift supports two kinds of comments: single-line comments and multi-line comments.
Single-Line Comment
The comments start with //
//This is a single-line comment
Multi-Line Comment
The comments enclosed between /* and */
/* This is a multi-line comment.
This is another line. */
Semicolons
Adding a semicolon (;) at the end of a statement is optional but allowed in Swift. However, we can use them to separate multiple statements on the same line as shown below.
var example = "DataFlair"; print(example)
Output:
DataFlair
Tokens, Identifiers & Keywords
Tokens are the smallest individual units in Swift. They are the core components of swift language. It also includes identifiers and keywords.
Identifiers are the names given to variables, classes, functions, and other elements in the code. It should begin with an alphabet (A-Z or a-z) or underscore (_). It may contain letters or numbers or underscore. Other characters like! @, #, etc are not allowed.
Note: Swift is a case-sensitive language. So, DataFlair and DataFlair are different.
// valid identifier DataFlair dataFlair _dataFlair //Not a valid identifier 1dataFlair DataFlair# _DataFlair@
Keywords are the reserved words in Swift. They have specific meanings and functionality. These cannot be used as identifiers. Using keywords ensures Swift code works as intended and follows the language’s rules.
Some examples of keywords are let, var, if, else, for, and so on.
Print keyword
We use the print function to display output to the console or other output streams. It takes one or more items as its arguments and displays them sequentially.
Items: Items are the values or variables that we want to display.
let name = "DataFlair"
print("Name: ", name)
Output:
Name: DataFlair
Separators: We use them to add a specific character or string between the items when they are displayed.
let exampleOne = "Tuples" let exampleTwo = "Optionals" let exampleThree = "Literals" print(exampleOne, exampleTwo, exampleThree, separator: ", ")
Output:
Tuples, Optionals, Literals
Terminators: It is the character or string that is added at the end of the print statement. By default, it is a new line (\n). But we can change it to something else.
let example1 = "Hello" let example2 = "From DataFlair" print(example1, terminator: "! ") print(example2)
Output:
Hello! From DataFlair
We can format our outputs as we require with the help of separators and terminators.
Type Annotations
Type annotations allow us to specify the datatype of an identifier. This feature enhances code clarity. It helps catch type-related errors during compile-time. It also aids in better code documentation. The syntax for type annotation involves using a colon (:) followed by the desired data type.
let name: String = "DataFlair" var year: Int = 2023
Type Aliases
Type aliases are alternative names for existing data types. By using the typealias keyword, we can define custom names for complex data types. They help to improve code readability when working with lengthy data types. It makes the codebase more maintainable and clear.
var example: (String, Int) // Original Type
typealias typeAliasExample = (name: String, age: Int) // Type Alias
var example1 : typeAliasExample = ("DataFlair", 2023) // Usage of Type Alias
White Spaces
Swift ignores the white spaces present in our code. White space includes spaces, tabs, and newlines. It is used for code formatting. It improves readability.
let example = "DataFlair" //white spaces are ignored.
Literals
Literals represent the fixed value in our code. Integer, Boolean, and String literals are some of the literals supported in Swift.
Integer Literals
Integer literals are used to represent whole numbers without fractional components. They can be either positive or negative and can be expressed in different formats like decimal, binary, octal & hexadecimal.
let integerLiteral: Int = 2023
String Literals
String literals represent a sequence of characters enclosed within double quotes. They can include any combination of letters, numbers, symbols, and even escape sequences for special characters.
let stringLiteral: String = "DataFlair"
Boolean Literals
Boolean literals represent boolean values, either true or false. They are commonly used for logical comparisons and control flow in our programs.
let booleanLiteral: Boolean = true
Import
The import keyword is used to include the external modules or frameworks in our code. It expands the capabilities of our code. It gives access to a wide range of features provided by different modules and frameworks. The predefined functionalities in these enhance our Swift program.
import module
Variables and Constants
In Swift, we declare variables using the var keyword and constants using the let keyword.
We can reassign the values of variables. We cannot change the constants after assigning their value once.
var variableExample: Int = 2023 //Declaration of variable let constantExample: String = "DataFlair" // Declaration of constant
Tuples
A tuple is a collection of two or more values bundled together into a single compound value. They can be of different data types. They are useful when we need to combine and pass around related pieces of data as a single unit. They can be accessed using both index and element names. They are flexible, so it makes them an excellent choice for returning multiple values from a function or temporarily grouping data together. It offers a simple yet effective solution for managing and organizing data efficiently.
let tupleExample: (String, Int) = ("DataFlair", 2023)
Optionals
An optional is a special data type in Swift that allows variables to have either a value or no value at all. By using optionals, we explicitly express that a variable might be empty. This assists the compiler in ensuring program safety.To define an optional, we append a question mark (?) to the type declaration. For instance:
var optionalString: String? // A variable that can hold text or be nil
Conclusion
Swift’s basic syntax forms the foundation for building applications on various Apple platforms. We’ve explored important concepts like comments, semicolons, tokens, identifiers, keywords, whitespaces, literals, and imports. Understanding these fundamentals allows us to write clean and efficient code. Whether you’re a beginner or an experienced coder, mastering these concepts will help you create robust and expressive Swift programs.
