Swift 學習筆記一 基礎資料型別 (Elementary Data Type)和簡單語句文法

來源:互聯網
上載者:User

標籤:xcode   swift   

第一個程式

建立xcode項目,語言選擇Swift

建立項目後可以直接Command+R運行。
修改程式ViewController.swift

////  ViewController.swift//  H?ello swift////  Created by 謝廠節 on 15/6/9.//  Copyright (c) 2015年 WHR. All rights reserved.//import UIKitclass ViewController: UIViewController {    override func viewDidLoad() {        super.viewDidLoad()        print("Hello Swift")        // Do any additional setup after loading the view, typically from a nib.    }    override func didReceiveMemoryWarning() {        super.didReceiveMemoryWarning()        // Dispose of any resources that can be recreated.    }}

運行後,輸出 Hello Swift.

可以看到整體架構與ObjectC很相似,文法有所不同。奇怪的是每行沒有用;結尾。

變數及邏輯文法變數定義
var a=42                    //變體類型,var用來定義變數a=50let constantVariable=100    //定義一個常量left double:Double = 10     //指定常量類型String(constantVariable)    //類型轉換,這比OC方便多了let merge="The first one is \(a)"      //字串中包含值var list=["a","b","c","d"]   //數組定義list[1] = "b1"                     //數組可以直接賦值了let emptyArray=String[]()   //定義空數組let emptyDictionary=Dictionary<String,list>()   //定義空詞典var cannil :String? = "abc"  //可選
迴圈
for item in list{}遍曆詞典和數組for (item,numbers) in array{    for opt in item{    }}
條件
if a>10 {   //蘋果為什麼不搞和c java 類似的文法呢}if let a=b{}
分支
 switch str{    case "a":    case "b":    default:}
迴圈
while i<10{    i=i+1;}for i in 0...3{   print(i)}for var i=0;i<3;++i{   print(i)}
函數
func hello(name:String)->String{   return "Hello \(name)"}

函數允許嵌套

Swift 學習筆記一 基礎資料型別 (Elementary Data Type)和簡單語句文法

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.