Created
October 10, 2014 05:49
-
-
Save alwold/617276d6203a1b939343 to your computer and use it in GitHub Desktop.
Swift tour playground
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
// Basic swift stuff | |
// constant | |
let x = 1 | |
//x = 2 // error | |
// variable | |
var y: Int = 2 | |
y = 3 | |
// arithmetic | |
x+y | |
// specifying type | |
var z: String = "Hello" | |
var foo = "World" | |
// interpolation | |
z = "Hello \(foo), the number is \(x+y)" | |
// concatenation | |
z + "hello" | |
// arrays | |
var arr = [1, 2, 3, 4] | |
var hash = ["foo": "bar", "x": "y"] | |
hash["foo"] | |
// for loop | |
for number in arr { | |
println(number) | |
} | |
// while loop | |
y = 1 | |
while y < 100 { | |
println(y) | |
y++ | |
} | |
// range - this used to be .. and ... | |
var myrange = 1...10 | |
1..<11 | |
1...x | |
for zzz in myrange { | |
print(zzz) | |
} | |
for zzz in 1..<10 { | |
print(zzz) | |
} | |
// optional type | |
var notoptional: String | |
var optional: String? | |
optional = "hello" | |
optional = nil | |
//var notoptional // error, no value defined | |
optional = "x" | |
// nice unwrapping | |
if let unwrapped = optional { | |
println(unwrapped) | |
} | |
// less nice unwrapping | |
optional! // this will crash if optional is nil | |
// functions - return value comes after the argument list | |
func addOne(value: Int) -> Int { | |
return value+1 | |
} | |
addOne(1) // 1+1=2 - you learn something every day | |
// tuples - awesome! | |
func giveMeSomeNumbers() -> (Int, Int, Int) { | |
return (1, 2, 3) | |
} | |
func hello() { | |
println("hello") | |
} | |
hello() | |
func twoArgs(arg1: String, #arg2: String) { | |
} | |
twoArgs("Hello", arg2: "World") | |
giveMeSomeNumbers() | |
// classes | |
class MyClass { | |
var x: Int // type is required | |
init(x: Int) { | |
self.x = x | |
} | |
func addToX(#amount: Int, more: Int) { | |
self.x += amount | |
self.x += more | |
} | |
func getX() -> Int { | |
return x // no need to specify self | |
} | |
} | |
var mc = MyClass(x: 1) // need to specify param name in constructors | |
mc.addToX(amount:2, more: 3) // but on methods, only the non-first arguments need names | |
mc.getX() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment