swift定义与赋值

1.常量和变量的定义
常量用 let 定义或赋值;变量用var定义;一个常量的值不需要在编译时已知,但是你必须给他指定一次值;也就是你用常量只需指定一次后在很多地方都可以用;常量或变量的值必须和你指定的值的类型一样;但是你无需去申明他的具体类型,如列子中myConstant是整形,因为他的值是整型;
var myVariable = 42
myVariable = 50
let myConstant = 42
如果没有提供足够的信息
let implicitInteger = 70
let implicitDouble = 70.0
let explicitDouble: Double = 70
如果是需要定义一个其他和原来不同类型
let label = “The width is ”
let width = 94
let widthLabel = label + String(width)
当将值写到圆括号内,必须在括号钱待上“/”
let apples = 3
let oranges = 5
let appleSummary = “I have \(apples) apples.”
let fruitSummary = “I have \(apples + oranges) pieces of fruit.”
定义数组
var shoppingList = [“catfish”, “water”, “tulips”, “blue paint”]
shoppingList[1] = “bottle of water”

var occupations = [
“Malcolm”: “Captain”,
“Kaylee”: “Mechanic”,
]
occupations[“Jayne”] = “Public Relations”

定义空数组和空字典
let emptyArray = String[]()
let emptyDictionary = Dictionary()
如果类型可推断
shoppingList = []
Dictionary =[:]

Posted in 未分类