Swift Tutorial - Tutorialspoint

(backadmin) #1

When we run the above program using playground, we get the following result:


42


Type Annotations


You can provide a type annotation when you declare a variable, to be clear about the
kind of values the variable can store. Here is the syntax:


var variableName:<data type> = <optional initial value>

The following example shows how to declare a variable in Swift using Annotation. Here it
is important to note that if we are not using type annotation, then it becomes mandatory
to provide an initial value for the variable, otherwise we can just declare our variable using
type annotation.


import Cocoa

var varA = 42
println(varA)

var varB:Float

varB = 3.14159
println(varB)

When we run the above program using playground, we get the following result:


42


3.1415901184082


Naming Variables


The name of a variable can be composed of letters, digits, and the underscore character.
It must begin with either a letter or an underscore. Upper and lowercase letters are distinct
because Swift is a case-sensitive programming language.


You can use simple or Unicode characters to name your variables. The following examples
shows how you can name the variables:


import Cocoa

var _var = "Hello, Swift!"
println(_var)
Free download pdf