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"
備註:使用起來像一個閉包


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