Created
December 31, 2014 00:07
-
-
Save guozheng/6825277f6c2e7e74669b to your computer and use it in GitHub Desktop.
gist to learn Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Playground - noun: a place where people can play | |
import UIKit | |
var str = "Hello, playground" | |
// array | |
var a1 = [1, 2] | |
var a2 = [3, 4] | |
var a3 = a1 + a2 | |
var b1 = [1.5, 2.5] | |
b1 += [2.4] | |
// dictionary | |
var d3 = ["Apple": 1, "Orange": 2] | |
println(d3["Apple"]) | |
d3 = [:] | |
// tuple | |
var t2 = (index: 1, value: "hello") | |
let (index, value) = t2 | |
println("index: \(index), value: \(value)") | |
// demo of closure | |
func square(a: Float) -> Float { | |
return a * a | |
} | |
func cube(a: Float) -> Float { | |
return a * a * a | |
} | |
func averageOfFunction(a: Float, b: Float, f: (Float -> Float)) -> Float { | |
return (f(a) + f(b)) / 2 | |
} | |
println("\(square(2)), \(square(4)), \(averageOfFunction(2, 4, square))") | |
// demo of array map, filter, reduce functions | |
var a4 = a3.map({$0 + 1}) // add 1 to each element in a3 | |
var a5 = a3.filter({$0 > 3}) // filter out elements smaller than 4 in a3 | |
var a6 = a3.reduce(0, {$0 + $1}) // use reduce to add up elements in a3 | |
var a7 = a3.reduce(0, +) // use reduce to add up elements in a3 | |
println("a3: \(a3), a4: \(a4), a5: \(a5), a6: \(a6), a7: \(a7)") | |
var s = "hello, world" | |
for scalar in s.unicodeScalars { | |
println(scalar) | |
} | |
func sayHi(greeting: String, #name: String) { | |
println("\(greeting), \(name)") | |
} | |
sayHi("hi", name: "Jobs") | |
func sayHi(greeting: String = "hello, world") { | |
println(greeting) | |
} | |
sayHi() | |
sayHi(greeting: "hi, earth") | |
var optionalVal: Int? | |
optionalVal = 1 | |
if let optionalVal = optionalVal { | |
println("optionalVal: \(optionalVal)") | |
} | |
var optionalValue: Int? = 1 | |
if let optionalValue = optionalValue { | |
println("The int was \(optionalValue)") | |
} else { | |
println("The int was not there.") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment