//var变量 let常量 常量不能更改
var myVariable = 42
let myConstant = 43
//常量不能改变
//cannot assign to 'let' value 'myConstant'
//myConstant = 44
let label = "hello world is"
let width = 1
//值永远不会被隐式转换为其他类型。如果你需要把一个值转换成其他类型,请显式转换。
//Could not find an overload for '+' that accepts the supplied arguments
//let widthLabel = label + width
//以下正确
let widthLabel = label + String(width)
let apples = 3
let oranges = 5
let appleSummary = "I hava \(apples) apples."
let fruitSummary = "I hava \(apples + oranges) fruit"
println(String(fruitSummary))
//使用方括号[]来创建数组和字典,并使用下标或者键(key)来访问元素。
var weather = ["spring", "summer", "autumn", "winter"]
weather[1] = "what"
var occupations = ["Malcolm": "Captain","Kaylee": "Mechanic",]
occupations["Jayne"] = "Public Relations"
//要创建一个空数组或者字典,使用初始化语法。
let emptyArray = String[]()
let emptyDictionary = Dictionary<String, Float>()
截图:
let arrayScore = [32, 323, 232, 232]
var teamScore = 0
for score in arrayScore {
if score > 50 {
teamScore += 3
} else {
teamScore += 1
}
}
teamScore
var optionalString: String? = "Hello"
optionalString == nil
var optionalName: String? = "John apple"
optionalName = nil
var greeting = "hello!"
//如果变量的可选值是 nil,条件会判断为 false,大括号中的代码会被跳过。如果不是 nil,会 将值赋给 let 后面的常量,这样代码块中就可以使用这个值了。
if let name = optionalName {
greeting = "Hello,\(name)"
} else {
greeting = "what the heal"
}
//switch 支持任意类型的数据以及各种比较操作——不仅仅是整数以及测试相等。
//运行 switch 中匹配到的子句之后,程序会退出 switch 语句,并不会继续向下运行,所以不 需要在每个子句结尾写 break。
let vegetable = "red pepper"
switch vegetable {
case "celery":
let vegetableComment = "Add some raisins and make ants on a log."
case "cucumber", "watercress":
let vegetableComment = "That would make a good tea sandwich."
case let x where x.hasSuffix("pepper"):
let vegetableComment = "Is it a spicy \(x)?"
default :
let vegetableComment = "Everything tastes good in soup."
}
截图: