Introduction of swift

Based on WWDC 2014.

variables & constants

var testName: String = “Swift”

let testName: String = “Swift”

Type Inference

let testName = “swift”    // inferred as string

unicode names

let T=””

String

urlRequest.HTTPMethod = “POST” + “test”

Character

for character in “sdfsf” {

}

String Interpolation

let mathResult = “\(a) times \(b) is \(a*b)”

String Mutability

var vatiableString could use + adding string, let constant string could not.

Array & Dictionary

var names = [“Anna”, “Alex”]

var Dict = [“anna”: 6]

Typed Collections

var names: String[] = [“anna”, “alex”]     //array of string values

Loop(while)

Loop(for-in )

for number in 1…5 {}    // from 1 to 5

for number from 0..5 {}    // from 0 to 4

Modifying an Array

shoppingList += “Flour”     // add an item for array

Modifying Dictionary

numberOfLegs[“spider”] = 8

Retrieving a value from a Dict

let possibleLegCount: Int? = numberOfLegs[“addrewa”]

if possibleLegCount == nil {} else {}

switch legCount {

case 0:  println(“hello”)

case 1…8:  println(“a few legs”)

default:  println(“others”)

}

Tuples 

(404, “not found”)   (2, “banana”, 1.7)

Closures

let greetingPrinter()->() = { println(“hello world!”)}

Class

class Vehicle {

let numberOfWheels = 0    //property

var description: String {    /computed property

get { return “\(numberOfWheels) wheels”}

}

let someVehicle = Vehicle()   // initialization

}

class Bicycle: Vehicle {

init() {

super.init()

numberOfWheels = 2

}

}

class Car: Vehicle {

var speed = 0.0

init () {

super.init()

numberOfWheels =4

}

override var description: String {

willSet {} didSet{}

}

}

Structures in SWIFT

var point = Point

struct Rect {

var origin: Point

var size: Size

var area: Double {

return size.width * size.height

}

}

var newFrame = window.frame

var point1 = Point(x:0.0, y:0.0)

Enumerations: Raw Values

enum CompassPoint {

case North, South, East, West

init(){

self = South    // powerful 

}

var description:String{}

}

 

var directionToHead = CompassPoint.West

direcionToHead = .East

Extensions

extension CGSize {

mutating func increaseByFactor(factor:Int) {

width *= factor

height *=factor

}

}

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s