1. 程式人生 > 其它 >【SWIFT】從零開始的SWIFT語言學習筆記-2:簡單值、陣列與字典

【SWIFT】從零開始的SWIFT語言學習筆記-2:簡單值、陣列與字典

1.0.3 簡單值、陣列與字典

知識點:

使用var建立變數

var myVariable = 65

myVariable = myVariable + 1

 

使用let建立常量

let myConstant = 67

 

在建立變數或常量的時候不需要特別指出其型別,編譯器會自動推斷。

如果一開始不確定,則可以使用冒號指定型別。

let myConstant0 = 1

let myConstant1:Double = 2.71

var myVariable0 = 3

var myVariable1:Float=3.14

 

Swift不會隱式轉換格式,我們需要在使用的時候準確轉換好值的型別。

我們需要顯式建立所需型別的例項。

let label = "My label"

let num = 1

let labelName = label + (String)(num)

 

字串中包含值有一種簡單的方法,使用\()取代複雜的寫法。

該運算子也可以包含運算。

let apples = 3

let oranges = 5

let appleSum = "I have " + String(apples) + " apples"

let orangeSum = "I have \(oranges) oranges"

let allSum = "I have \(oranges + apples) things"

 

對佔用多行的文字使用“”“。當“”“匹配時,就可以取消開頭的縮排。

let longString = """

我:你好,我有\(apples)個蘋果

她:你好,我有\(oranges)個橙子

結束對話

"""

 

使用[]建立陣列和字典,在方括號輸入索引訪問其元素。最後一個元素後面允許有逗號。

索引從0開始。

var shoppingList = ["pen","apple","water",]

var firstItem = shoppingList[0]

var peopleList = [

    "peter":"Teacher",

    "sam":"Student",

]

 

增加陣列或字典長度

peopleList["Jason"] = "Chef"

shoppingList.append("hat")

print(peopleList)

print(shoppingList)

 

如果要建立空陣列字典,使用初始化語法

var emptyArray:[String]=[]

var emptyDictionary:[String:Float]=[:]

 

如果已確認陣列型別,就使用[]清空陣列,[:]清空字典,如下:

emptyArray = []

emptyDictionary = [:]

練習題

1.建立一個具有Float顯式型別且的值為4的常量.

Create a constant with an explicit type of Float and a value of 4.

 

2.若 let widthLabel = label + String(width) 程式碼中的的強制轉換刪除會出現什麼錯誤?

Try removing the conversion to String from the last line. What error do you get?

 

3.使用\()語法構建一段文字,要求包含浮點數計算和某人姓名。

Use \() to include a floating-point calculation in a string and to include someone’s name in a greeting.


下一章,我們學習Control Flow控制流,if switch等等語句的使用