swif study

基本

变量和常量

使用let定义常量,使用var定义变量,定义时可以不指定变量类型,swift会根据 初始值推算变量类型,如果指定类型,在变量名的冒号后面指定。

var a = 70  //integer
var a = 70.0 //double
let a:Double = 70 //double

swift不会进行任何隐式转换,你必须进行显示转换,你可以使用\转换为string

let apples = 3
let oranges = 5
let appleSummary = "I have \(apples) apples"
let fruitSummary = "I have \(apples + oranges) pieces of fruit"

使用[]创建数组和字典

let emptyArray = String[]()
var shoppingList = ["1","2"]
shoppingList[1] = "3"

let emptyDictionary = Dictionary<String, Float>
var occupations = [
  "1":"2",
  "3":"4",
]

occupations["5"] = "6"

你可以使用[]或[:]创建新的数组或字典,当给变量赋值或传入函数参数时: