转载链接:http://www.cocoachina.com/newbie/basic/2014/0604/8675.html
备忘录:http://www.cocoachina.com/applenews/devnews/2014/0604/8663.html
1. SWift我来了,hello world!
- println("hello, world")
备注:
这行代码就是一个完整的程序,不需要导入库,不需要main函数入口,末尾连分号也不再需要。
2. 使用let来声明常量,使用var来声明变量
- var myVariable = 42
- myVariable = 50
- let myConstant = 42
- let implicitInteger = 70
- let implicitDouble = 70.0
- let explicitDouble: Double = 70
值永远不会被隐式转换为其他类型。如果你需要把一个值转换成其他类型,请显式转换
例如:String() 或 \()
- let width = 30
- let widthLable = "The width is \(width)"
- let widthLabel1 = "The width is" + String(width)
- let widthLable2 = "Phone" + " width is \(width)"
3. 使用方括号[]来创建数组和字典,并使用下标或者键(key)来访问元素。
- var shoppingList = ["catfish", "water", "tulips", "blue paint"]
- shoppingList[1] = "bottle of water"
- var occupations = [
- "key1": "value1",
- ]
- occupations["key2"] = "value2"
- occupations["key1"] = "value111"
- let emptyArray = String[]()
- let emptyDictionary = Dictionary<String, Float>()
3. Swith中运行switch中匹配到的子句之后,程序会退出switch语句,并不会继续向下运行,所以不需要在每个子句结尾写break
- let vegetable = "red pepper"
- switch vegetable {
- case "celery":
- let vegetableComment = "Add some raisins and make ants on a log."
- case "cucumber", "watercress":
- let vegetableComment = "That would make a good tea sandwich."
- case let x where x.hasSuffix("pepper"):
- let vegetableComment = "Is it a spicy \(x)?"
- default:
- let vegetableComment = "Everything tastes good in soup."
- }
- let n = 2
- switch n {
- case 1:
- println("It's 1!")
- case 2...4:
- println("It's between 2 and 4!")
- case 2..4:
- println("It's between 2 and 3!")
- case 5, 6:
- println("It's 5 or 6")
- default:
- println("Its another number!")
- }
4. 使用func来声明一个函数,使用名字和参数来调用函数。使用->来指定函数返回值。
- func greet(name: String, day: String) -> String {
- return "Hello \(name), today is \(day)."
- }
- greet("Bob", "Tuesday")