【SWIFT】从零开始的SWIFT语言学习笔记-2:简单值、数组与字典

2022-10-17,,,,

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等等语句的使用

【SWIFT】从零开始的SWIFT语言学习笔记-2:简单值、数组与字典的相关教程结束。

《【SWIFT】从零开始的SWIFT语言学习笔记-2:简单值、数组与字典.doc》

下载本文的Word格式文档,以方便收藏与打印。