Swift的未来趋势我就不言论了,去年写过基本代码,现在要用,只能系统再过一遍!
let做常量var做变量。常量值在编译中并不需要被知道,但是必须一次性精确的进行赋值:也就是说只能在在定义的时候赋值一次,但是可以多次使用
var myVariable = 42
myVariable = 50
let myConstant = 42
myVariable = 50
let myConstant = 42
常量和变量在设定值时必须采用相同格式。但并不需要定义精准的类型。创建一个常量或变量时提供一个值,让编译器判断其类型。在上面的例子中,编译器指定myVariable是一个整数,因为它的初始值是整数。
若初始化时未提供足够信息(没有初始值),可以在变量后面指定类型,用冒号隔开。
let implicitInteger = 70
let implicitDouble = 70.0
let explicitDouble: Double = 70
let implicitDouble = 70.0
let explicitDouble: Double = 70
练习:创建一个类型是Float的,值为4的常量
值在转化为另一种类型时从不具有隐含性。如果需要转化值到另一种类型,请明确性地为值进行格式转换。
let label = "The width is "
let width = 94
let widthLabel = label + String(width)
let width = 94
let widthLabel = label + String(width)
试着将最后一行的 String 转换去掉,你会得到什么错误?
更简单的方法将值转换为String:将值写在括号中,并在括号前添加一个反斜杠。例:
let apples = 3
let oranges = 5
let appleSummary = "I have \(apples) apples."
let fruitSummary = "I have \(apples + oranges) pieces of fruit."
let oranges = 5
let appleSummary = "I have \(apples) apples."
let fruitSummary = "I have \(apples + oranges) pieces of fruit."
通过[]创建一个数组和字典,通过 index 和 key 获取对应的值
var shoppingList = ["catfish","water","tulips","blue paint"]
shoppingList[1] = "bottle of water"
var occupations = [
"Malcolm": "Captain",
"Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations"
shoppingList[1] = "bottle of water"
var occupations = [
"Malcolm": "Captain",
"Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations"
创建空数组和字典,以及初始化语法。
let emptyArray = String[]()
let emptyDictionary = Dictionary<String,Float>()
let emptyDictionary = Dictionary<String,Float>()
为了防止类型信息被更改,空数组列用[],空字典用[:]进行初始化 - 例如,为变量赋新值和给函数传递参数的时候。
shoppingList = [] // Went shopping and bought everything
原文链接:https://www.f2er.com/swift/323173.html