constant
- oc中:const double PI = 3.1415927;
- // oc中的关键字const来自c语言。使用较为复杂,代表值不变。
- swift中:let PI:Double = 3.1415927;
tuple(元组)
- oc中在返回多个值的时候使用数组或者字典。由于数组只能包含一种类型数据,字典虽然可以定义多种类型,但是使用起来更为复杂,需要为每一个数据指定名称。
- swift可以用tuple直接封装多种类型的数据。在传递参数和获取返回值,更方便。
- 使用方法为(32,"32",[32,32],[32:"32"])
optional
- optional实际上是一个enum类型
- 主要设计用来覆盖一个参数没有默认值或者未被赋值的情况,例如接口的返回值某个字段就可能没有。
- 杜绝了空指针可能引起的错误
- 只有两种情况,要么为nil,要么为一个确定的值
- optional可以用来封装所有类型
类型安全
字符串插值
- print("The current value of friendlyWelcome is (friendlyWelcome)")
- print方法默认以\n结尾,可以通过print(someValue, terminator: "")删除\n
- print(#"Write an interpolated string in Swift using (multiplier)."#)使用##输出原始字符串
- print(#"6 times 7 is \ #(6 * 7)."#) 在原字符串中,指定某些变量。
子数组
for name in names[2...] {
print(name)
}
// Brian
// Jack
for name in names[...2] {
print(name)
}
格式化字符串
let quotation = """
The White Rabbit put on his spectacles. "Where shall I begin,
please your Majesty?" he asked.
"Begin at the beginning," the King said gravely, "and go on
till you come to the end; then stop."
"""
字符串初始化
var emptyString = "" // empty string literal
var anotherEmptyString = String() // initializer syntax
// these two strings are both empty, and are equivalent to each other