position: fixed; top: auto !important; margin-left: 112px;

Swift Constants

A constant is an entity that doesn’t change whereas a variable is an entity that may change.

For example, when we write

int a = 10
int a = 20
int a = 30

'a' is variable & '10' is constant. Variable 'a' value can be changed to '20' or '30' but you cannot change '10' or '20' or '30' . These are constant values . In simple words , just a number in this example .

Constant Declaration in Swift :

To declare constants in Swift 'let' keyword is used. Semicolons are not compulsory in Swift Language. But remember if you add two statements in a single line you have to use ';' as delimiter to separate them. Otherwise, it shows syntax error.

Syntax :-

let constantName = Constant Value

Example :-

let name = "Manish"
let a = 20
let b = 20.0

Let's create a sample playground , Goto File > New > Playground > Next.


Example:

import UIKit
let a = 20
print(a)

Run the program in the playground.

Output:

20

Type Annotations

Annotations are used to specify the type to constant. With the help of Type Annotations it will be clear what kind of value that specific constant can store. And this can be done by placing a colon after the constant or variable name, followed by a space, followed by the name of the type to use.

Syntax:

let constantName:<data type> = <optional initial value>

Example :-

import UIKit
let name: String
name = "Manish"
print(name)

let varA:Float = 30.0
print(varA)

Output :-

Manish
30.0

Print in Swift 3.1

//: Playground - noun: a place where people can play

import UIKit

let name = "Manish"
var age = 23

print("\(name) age is = \(age)")

Output :-

Manish age is = 23

Previous Next Article







codzify.com


Largest collection of up-to-date tutorials to learn programming languages. We are focused on easy learning. Massive collection of interview questions one may need for preparation.

Social Profile


Linkedin
Twitter
Facebook

Copyright 2018. All rights reserved.