var myInt = 1 var myExplicitInt: Int = 1// explicit type var x = 1, y = 2, z = 3// declare multiple integers myExplicitInt = 2// set to another integer value
字符串
1 2 3 4 5 6 7 8
var myString = "a" let myImmutableString = "c" myString += "b"// ab myString = myString + myImmutableString // abc myImmutableString += "d"// compile-time error!
letcount = 7 let message = "There are \(count) days in a week"
字典
1 2 3 4 5 6 7
var days = ["mon": "monday", "tue": "tuseday"] days["tue"] = "tuesday"// change the value for key "tue" days["wed"] = "wednesday"// add a new key/value pair
var moreDays: Dictionary = ["thu": "thursday", "fri": "friday"] moreDays["thu"] = nil// remove thu from the dictionary moreDays.removeValueForKey("fri") // remove fri from the dictionary
枚举
1 2 3 4 5
enumCollisionType: Int{ casePlayer = 1 caseEnemy = 2 } var type = CollisionType.Player
//SWITCH STATEMENT let n = 2 switch n { case1: println("It's 1!") case2...4: println("It's between 2 and 4!") case5, 6: println("It's 5 or 6") default: println("Its another number!") } // It's between 2 and 4!
forvar index = 1; index < 3; ++index { // loops with index taking values 1,2 } for index in1..3 { // loops with index taking values 1,2 } for index in1...3 { // loops with index taking values 1,2,3 }
let colors = ["red", "blue", "yellow"] for color in colors { println("Color: \(color)") } // Color: red // Color: blue // Color: yellow
let days = ["mon": "monday", "tue": "tuesday"] for (shortDay, longDay) in days { println("\(shortDay) is short for \(longDay)") } // mon is short for monday // tue is short for tuesday
函数
1 2 3 4 5 6 7 8 9
funciAdd(a: Int, b: Int) -> Int { return a + b } iAdd(2, 3) // returns 5
var happy = true var sad = !happy // logical NOT, sad = false var everyoneHappy = happy && sad // logical AND, everyoneHappy = false var someoneHappy = happy || sad // logical OR, someoneHappy = true
打印(输出)
1 2 3 4 5 6 7 8 9 10
let name = "swift" println("Hello") println("My name is \(name)") print("See you ") print("later") /* Hello My name is swift See you later */