Swift基礎用法(Swift開發之一)

來源:互聯網
上載者:User

昨晚蘋果發布了新一代程式設計語言Swift,官方提供了一個iBook的說明文檔,有需要的可以看下。地址:https://itunes.apple.com/cn/book/swift-programming-language/id881256329?mt=11


下面我先說下基本的一些東西,大家都是剛看,所以我也難免會出現理解錯誤的地方。歡迎指出。當然你也可以直接看官方的文檔。


一、let,var基本類型

let:常量,不能二次賦值。賦值時可以不需要指定類型,編譯器根據賦值自動判斷。也可以手工指明類型。
var:變數

let a = 12 // 申明a為常量12,類型Intlet b: Double = 12 // 申明a為常量12,手工指定類型Double


二、字串

1、加號可以直接拼接字串,不能直接拼接其他類型轉化成string
 
let str = "Hello, playground. "let name = "Tom "let count = 10let say = str + name + String(count)  // "Hello, playground. Tom 10"


2、 字串中直接引入代碼
let a = 1let b = 2let say = "the number is \(a + b)"  // "the number is 3"


三、數組、字典 都可以直接使用 [] 聲明

1、數組
var arr = ["catfish", "water", "tulips", "blue paint"]arr[1] = "bottle of water" // 修改第二項arr // ["catfish", "bottle of water", "tulips", "blue paint"]


2、字典
var man = [    "like": "apple",    "name": "Tom",]man["iphone"] = "5s"  // 增加欄位man["like"] = "mac"  // 修改欄位man // ["iphone": "5s", "like": "mac", "name": "Tom"]


四、控制語句

1、if  不可以直接使用一個變數或者常量來作為條件,必須是判斷語句
let a = 12if a > 0 {    // do something} else {   // do something}

如果你寫成 if a {} ,就會報錯,不能直接使用變數或常量判斷bool


2、for
for i in 0..3 {   // i = 0, 1, 2}for var i = 0; i < 3; ++i {    // i = 0, 1, 2}// 數組let scores = [1, 2, 3, 4, 5]for score in scores {    // score }// 字典let numsDic = [    "a": [2, 3, 5, 7, 11, 13],    "b": [1, 1, 2, 3, 5, 8],    "c": [1, 4, 9, 16, 25],]for (key, numbers) in numsDic {    for number in numbers {        // number    }}


3、while
var n = 2while n < 100 {    n = n * 2}var m = 2do {    m = m * 2} while m < 100


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.