Open In App

Swift – Basic Syntax

Last Updated : 03 Jan, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Swift is a broadly useful programming language which is created by Apple Inc. It is an amazing programming language for iOS, iPadOS, macOS, tvOS, and watchOS. It incorporates present-day highlights engineers love. Swift code is protected by plan and furthermore delivers programming that runs lightning-fast. In this article, we will learn the basic syntax of the Swift programming language.

Identifiers

Identifiers are names used to recognize a variable, work, or other user-defined things. It should begin with an alphabet A to Z or a to z or an underscore with letters, underscores, and digits. Swift is a case-sensitive language along these lines, A and a are two distinct things. It doesn’t permit exceptional characters to be utilized in identifiers, for example, @, #, %, and so on.

Examples:

a, _temp, Temp, a_bc, a29b, temp12, temp_11

If you want to reserve a word as an identifier then use backtick(`) before and after the word. For example: `GeeksforGeeks`.

Keywords

Keywords are predefined, reserved words used in programming that have special pre-defined meanings. Keywords are part of the syntax and cannot be used as variable names and identifiers or any other user-defined items. Some pre-defined keywords are:

Class Func Let public deinit Enum extension import Init internal
operator private protocol static struct subscript typealias var break case
continue default do else fallthrough for if in return switch
where while as dynamicType false is  nil self Self super
true _COLUMN_ _FILE_ _FUNCTION
_
_LINE_ associativity convenience dynamic didSet final
get infix inout lazy left mutating none nonmutating optional override
postfix precedence prefix Protocol required right set Type unowned weak
willSet                  

Semicolons (;) 

The semicolon is used to separate multiple statements in programming languages. In Swift, we don’t need to write a semicolon at the end of every statement it’s optional and if we write a semicolon in our code it works the same as without a semicolon. But if we use multiple statements in a single line then we have to use the semicolon at the end of every statement.

// They both are same
var a = 1;
var b = 2

//We have to use semicolon if we will use more than one statements in the same line
var c = 3; print(c)

Example:

Swift




// Swift program to illustrate the use of semicolon
import Swift
  
var x = "GeeksforGeeks"; print(x)


Output:

GeeksforGeeks

Whitespaces

Whitespace is a blank space between two words. It separates one part of the statement from another part. It helps the compiler to identify which is a keyword and which is an identifier and whats their value is. There must be whitespace between a keyword and identifier. There is no whitespace necessary between two identifiers while doing any operations but it’s good for readability and easy to maintain the codes.

//It's mandatory to insert whitespace between var & temp
var a = 1
var b=2

// Both are valid but first is better in terms of readability
var c = a + b
var d =    a+b  

Literals

A literal is a notation for representing a fixed value in the codes. In Swift, we have notations values such as integers, floating-point numbers, strings, booleans, and characters. An anonymous function is literal for the function type.

// Here 1 is integer literal
var a = 11

// Here 11.123 is float literal
var b = 11.123

// Here GeeksforGeeks is String literal
var c = "GeeksforGeeks"

Comments 

Comments are the lines in the program which don’t get compiled by the compiler. It helps us to make the program clearly understandable. Or we can say that it is a programmer-readable explanation or annotation in the program or source code. They are added fully intent on making the source code more straightforward for people to comprehend.

Single line command syntax:

// Single line comment in Swift

Multi-line comment syntax:

/* multiple line comment syntax
We can write multiple lines here */

Print Statement

In many programming languages, print is a function that sends a text, variables, or another object to the screen. The sentence structure of how the print work functions might differ contingent upon the programming language. In Swift to print anything to the result screen, we are utilizing the print keyword.

// This will print the line which is present in the quotation mark
print("Welcome to GeeksforGeeks"

// This will print value of variable
var a = 5
print(a)

// This will print the value after doing computation
print(1 + 2)

Example:

Swift




// Swift program to illustrate print statement
import Swift
  
// Declaraig variables
var a = 1
var b = 1
  
if (a == b)
{
    print("Equal")
}
else
{
    print("Not Equal")
}


Output:

Equal

Import Class

The import can be used to import definitions from another Swift file. Swift organizes code into modules. Every module shows a namespace and upholds access controls on what portions of that code can be utilized outside of the module. A program might have all of its code in a single module, or it might import other modules as dependencies. We can use the import statement to import any library into your Swift program.

Syntax:

import module

Swift




// Swift program to illustrate import
import Swift
print("Hello Geeks!")


Output:

Hello Geeks!

Variables

In Swift, variables are used to store the values in the memory and we can perform different types of operations of the values of the variables. The value of the variable is not fixed just like the constant, we can change the value of the variable throughout the program. We can declare a variable with the help of var keyword:

Syntax:

var Variablename = Value

We are allowed to declare multiple variables in a single line separated by comma(,). For example, var a = 100, b = 304.

Example:

Swift




// Swift program to illustrate variables
import Swift
  
// Declaring variables
var a = 10
var b = 11
  
var c = a + b
  
print("Sum of a & b = \(c)")


Output:

Sum of a & b = 21

Constants

In Swift, constant means a fixed value. Or we can say that when a variable is declared as a constant then the value of the constant cannot be changed throughout the program. We can declare a constant using the let keyword:

Syntax:

let Constatname = Value

We are allowed to declare multiple constants in the single line separated by comma(,). For example, let a = 10, b = 34.

Example:

Swift




// Swift program to illustrate constants
  
// Declaring constant
let Res = "GeeksforGeeks"
  
print(Res)


Output:

GeeksforGeeks


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads