Swift: the beginning
NO Semicolons
Variables (and strings) var variable_name:Type = initial_value
var name_variable:String
var name:String= "Hello"
// intialize to a string
var name = "Hello" //notice I did not type it as a String---swift figures it out by initialization value
Constants
let constant_name:Type = initial_value
Examples
let name:String= "Hello" // intialize to a string
let name = "Hello" //notice I did not type it as a //String---swift figures it out by initialization value
Data Types
Print
println(“Hello /(var_name)” )
Above will print out:
Hello value_variable
Functions
Example funtion with no return or parameters
func sayHello() {
println(“hello”)
}
To invoke this function
sayHello()
Example function with parameters
NOTE:
nameofPerson declaration is used when expose definition of this function
func sayHelloToName(nameOfPerson name: String) {
println(“hello \(name)”)
}
To invoke this function
sayHelloToName(nameOfPerson: “Lynne”)
Example function with parameters
func sayHelloToName(name: String) {
println(“hello \(name)”)
}
To invoke this function
sayHelloToName(: “Lynne”)
Example, return a string (see declaration -> String)
func sayHelloToName(name: String) -> String {
println(“hello \(name)”)
return “Hello to you to!”
}
To invoke this function
var message:String = sayHelloToName(“Lynne”)
Example function with return of a tuple – 2 values
func sumCeil(a:Int, b:Int) -> [Int, Int] {
var ceil =a > b ? a : b
var sum = a+b
return (sum, ceiling)
}
To invoke this function
var total:Int = sumCeil(2, 33)
println( “values are sum= /(total.sum) and ceiling = /(total.ceil)”)
// NOTE: total.0 = sum value AND total.1 = ceiling
Example function with return of a tuple – 2 values
func sumCeil(a:Int, b:Int) -> [sum:Int, ceil:Int] {
var ceil =a > b ? a : b
var sum = a+b
return (sum, ceiling)
}
To invoke this function
var total:Int = sumCeil(2, 33)
// NOTE: total.sum = sum value AND total.ceil = ceiling
Creating Instance of Class
Call Constructor
Example, using UIView that is part of iOS UIKit package
import UIKit
var view = UIView()
view.backgroundColor = UIColor.yellowColor()
Classes
|