苹果公司推出的新编程语言Swift简介和入门教程

2020-01-08 22:32:28于海丽

 

复制代码
let label = "The width is "
let width = 94
let width = label + String(width)

 


1.4.字符串格式化

Swift使用(item)的形式进行字符串格式化:

复制代码
let apples = 3
let oranges = 5
let appleSummary = "I have (apples) apples."
let appleSummary = "I have (apples + oranges) pieces of fruit."

 


1.5.数组和字典

Swift使用[]操作符声明数组(array)和字典(dictionary):

复制代码
var shoppingList = ["catfish", "water", "tulips", "blue paint"]
shoppingList[1] = "bottle of water"
var occupations = [
    "Malcolm": "Captain",
    "Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations"

 

一般使用初始化器(initializer)语法创建空数组和空字典:

复制代码
let emptyArray = String[]()
let emptyDictionary = Dictionary<String, Float>()

 

如果类型信息已知,则可以使用[]声明空数组,使用[:]声明空字典。

2.控制流

2.1概览

Swift的条件语句包含if和switch,循环语句包含for-in、for、while和do-while,循环/判断条件不需要括号,但循环/判断体(body)必需括号:

 

复制代码
let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0
for score in individualScores {
    if score > 50 {
        teamScore += 3
    } else {
        teamScore += 1
    }
}

 

2.2可空类型

结合if和let,可以方便的处理可空变量(nullable variable)。对于空值,需要在类型声明后添加?显式标明该类型可空。

复制代码