Swift学习第一天

转载链接:http://www.cocoachina.com/newbie/basic/2014/0604/8675.html

备忘录:http://www.cocoachina.com/applenews/devnews/2014/0604/8663.html


1. SWift我来了,hello world!

  1. println("hello, world"
备注:这行代码就是一个完整的程序,不需要导入库,不需要main函数入口,末尾连分号也不再需要。

2. 使用let来声明常量,使用var来声明变量
  1. var myVariable = 42 
  2. myVariable = 50 
  3. let myConstant = 42 
自动检测类型
  1. let implicitInteger = 70 
  2. let implicitDouble = 70.0 
  3. let explicitDouble: Double = 70 
值永远不会被隐式转换为其他类型。如果你需要把一个值转换成其他类型,请显式转换
例如:String() 或 \()
  1. let width = 30
  2. let widthLable = "The width is \(width)"
  3. let widthLabel1 = "The width is" + String(width)
  4. let widthLable2 = "Phone" + " width is \(width)"
3. 使用方括号[]来创建数组和字典,并使用下标或者键(key)来访问元素。
  1. var shoppingList = ["catfish""water""tulips""blue paint"
  2. shoppingList[1] = "bottle of water" 
  3.   
  4. var occupations = [ 
  5.     "key1""value1"
  6. occupations["key2"] = "value2" 
  7. occupations["key1"] = "value111" 
要创建一个空数组或者字典,使用初始化语法
  1. let emptyArray = String[]() 
  2. let emptyDictionary = Dictionary<String, Float>() 

3. Swith中运行switch中匹配到的子句之后,程序会退出switch语句,并不会继续向下运行,所以不需要在每个子句结尾写break

  1. let vegetable = "red pepper" 
  2. switch vegetable { 
  3. case "celery"
  4.     let vegetableComment = "Add some raisins and make ants on a log." 
  5. case "cucumber""watercress"
  6.     let vegetableComment = "That would make a good tea sandwich." 
  7. case let x where x.hasSuffix("pepper"): 
  8.     let vegetableComment = "Is it a spicy \(x)?" 
  9. default
  10.     let vegetableComment = "Everything tastes good in soup." 
  1. let n = 2 
  2. switch n { 
  3. case 1: 
  4.     println("It's 1!"
  5. case 2...4: 
  6.     println("It's between 2 and 4!"
  7. case 2..4: 
  8. println("It's between 2 and 3!"
  9. case 5, 6: 
  10.     println("It's 5 or 6"
  11. default
  12.     println("Its another number!"
备注:...是右闭区间 ..则相反

4. 使用func来声明一个函数,使用名字和参数来调用函数。使用->来指定函数返回值。
  1. func greet(name: String, day: String) -> String { 
  2.     return "Hello \(name), today is \(day)." 
  3. greet("Bob""Tuesday"
备注:使用起来像一个闭包


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章