Swift is a powerful and intuitive programming language for iOS, OS X, and watchOS.

• Data types

swift

 

• Variables and Constants Declaration

// Declaring Variable
var mutableDouble: Double = 1.0
mutableDouble = 2.0

//Declaring Constant
let constantDouble: Double = 1.0

//Declaring Optional
var optionalDouble: Double? = nil
optionalDouble = 1.0

 

• Enums

enum CollisionType: Int {
case Player = 1
case Enemy = 2
}

 

• Flow Control Statements

var condition = true
// If – else – condition

if condition {
// stmts
} else {
// stmts
}

var val = 5

// switch – case

switch val {
case 1: “foo”
case 2: “bar”
default: “baz”
}

// omits upper value, use … to include
for i in 0… Int {
return 0
}
func doIt(a:Int) -> Int {
return a
}
func doIt(a:Int, b:Int) -> Int {
return a+b
}

 

• Creating/Using an Instance

var a = MyClass()
a.myProperty
a.doIt()
a.doIt(1)
a.doIt(2, b:3)

 

• String Example

var personOne = “Krishna”
var personTwo = “Kumar”
var combinedString = “\(personOne): Hello, \(personTwo)!”

var tipString = “2499”

var tipInt = NSString(string: tipString).intValue
tipString = “24.99”

var tipDouble = NSString(string: tipString).doubleValue

 

• Array Example

var person1 = “Krishna”
var person2 = “Kumar”
var array:[String] = [person1, person2]
array.append(“Kranthi”)
for person in array {
print(“person: \(person)”)
}

var kranthi = array[2]

 

• Dictionary Example

var dict:[String: String] = [“Frog”: “Kermit”, “Pig”: “Piggy”, “Dog”: “Trixy”]
dict[“Dog”] = “Bujji”
dict[“Frog”] = nil // delete frog

for (type, name) in dict {
print(“type: \(type), muppet: \( name)”)
}

Bajibabu
Bajibabu
Software Engineer