Swift 基本语法
Simple Values
使用 let 定义常量,var 定义变量。常量的值虽然不必在编译阶段知道,但必须要赋一次值。
var myVariable = 42
myVariable = 50
let myConstant = 42
常量与变量的类型在定义时可以不用显式指定,编译器会根据所赋值进行推导。上例中,myVariable 变量值是整型故其类型是整型。
如果所赋值并未提供足够的信息,我们可以在定义时指定其类型,通常是在变量名后跟 : Type
let implicitInteger = 70
let implicitDouble = 70.0
let explicitDouble: Double = 70
如想在字符串中引入值类型,可通过 \() 实现:
let apples = 3
let oranges = 5
let appleSummary = "I have \(apples) apples."
let fruitSummary = "I have \(apples + oranges) pieces of fruit."
使用三引号 (""") 定义多行字符串:
let quotation = """
Even though there's whitespace to the left,
the actual lines aren't indented.
Except for this line.
Double quotes (") can appear without being escaped.
I still 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 = [String: Float]()
在某些可以推导出类型信息的场景下,可以使用 [] 和 [:] 来创建空数组和空字典,例如当你为变量赋新值或向函数传递参数。
shoppingList = []
occupations = [:]
Control Flow
使用 if 和 switch 做条件判断,for-in, while 和 repeat-while 进行循环操作。条件判断和循环变量周围的小括号是可选的,但 body 体的大括号是必要的。
let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0
for score in individualScores {
if score > 50 {
teamScore += 3
} else {
teamScore += 1
}
}
print(teamScore)
在 if 语句中,条件表达式必须是布尔类型的,这就意味着 if score {...} 是错误的,它不会隐士的与0进行比较。
使用 if let 处理那些变量值可能为空的情况,这些值以 optional 的形式表示。optional 的变量要么有值,要么为 nil。通常在变量类型之后添加 ? 表示其值为 optional。
var optionalString: String? = "Hello"
print(optionalString == nil)
var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
if let name = optionalName {
greeting = "Hello, \(name)"
}
如果 optional 值为 nil,那么条件判断为 false 大括号中的代码不会被执行。否则,optional 值会拆箱并赋值给常量 name。
使用 optional 值时可通过 ?? 操作符提供默认值,如果 optional 值为 nil,则使用默认值。
let nickName: String? = nil
let fullName: String = "John Appleseed"
let informalGreeting = "Hi \(nickName ?? fullName)"
Switch 语句支持多种数据类型和比较操作,它们并不局限于整型和相等性测试。
let vegetable = "red pepper"
switch vegetable {
case "celery":
print("Add some raisins and make ants on a log.")
case "cucumber", "watercress":
print("That would make a good tea sandwich.")
case let x where x.hasSuffix("pepper"):
print("Is it a spicy \(x)?")
default:
print("Everything tastes good in soup.")
注意到上例中如何在模式中使用 let 将匹配的值赋予常量 x。
执行完 switch case 语句后,程序会退出 switch 语句,并不会执行下一个 case,所以不必在每个 case 结束位置显式的添加 break。
使用 for-in 语句遍历字典,字典是无序的集合,故在遍历的其键和值时也是无序的。
let interestingNumbers = [
"Prime": [2, 3, 5, 7, 11, 13],
"Fibonacci": [1, 1, 2, 3, 5, 8],
"Square": [1, 4, 9, 16, 25],
]
var largest = 0
for (kind, numbers) in interestingNumbers {
for number in numbers {
if number > largest {
largest = number
}
}
}
print(largest)
使用 while 进行循环操作:
var n = 2
while n < 100 {
n *= 2
}
print(n)
var m = 2
repeat {
m *= 2
} while m < 100
print(m)
使用 ..< 创建下标范围,..< 包含下限不包含上限,... 包含上下限。
Functions and Closures
使用 func 关键字定义函数,函数的返回值类型写在声明的最后并用 -> 分隔。
func greet(person: String, day: String) -> String {
return "Hello \(person), today is \(day)."
}
greet(person: "Bob", day: "Tuesday")
默认情况下,函数使用参数名作为 labels。可在参数名前添加自定义标签,或者添加 _ 表示该参数无标签。
func greet(_ person: String, on day: String) -> String {
return "Hello \(person), today is \(day)."
}
greet("John", on: "Wednesday")
使用元组创建复合值,例如从函数中返回多个值。元组中的元素既可通过 name 也可通过 number 访问。
func calculateStatistics(scores: [Int]) -> (min: Int, max: Int, sum: Int) {
var min = scores[0]
var max = scores[0]
var sum = 0
for score in scores {
if score > max {
max = score
} else if score < min {
min = score
}
sum += score
}
return (min, max, sum)
}
let statistics = calculateStatistics(scores: [5, 3, 100, 3, 9])
print(statistics.sum)
print(statistics.2)
函数的定义可以嵌套,内层函数可以访问定义在外层的变量。
func returnFifteen() -> Int {
var y = 10
func add() {
y += 5
}
add()
return y
}
returnFifteen()
函数是 first-class 类型,因而函数可以作为函数返回值。
func makeIncrement() -> ((Int) -> Int) {
func addOne(number: Int) -> Int {
return 1 + number
}
}
var increment = makeIncrement()
increment(7)
函数可作为参数传入另一函数:
func hasAnyMatches(list: [Int], condition: (Int) -> Bool) -> Bool {
for item in list {
if condition(item) {
return true
}
}
return false
}
func lessThanTen(number: Int) -> Bool {
return number < 10
}
var numbers = [20, 19, 7, 12]
hasAnyMatches(list: numbers, condition: lessThanTen)
函数是特殊类型的闭包。闭包中的代码可以访问闭包创建上下文中定义的变量和函数,即使闭包在不同的区域执行。使用 {} 定义闭包,通过 in 关键字将 body 与参数和返回类型分开。
numbers.map({(number: Int) -> Int in
let result = 3 * number
return result
})
如果闭包的类型是已知的,例如 callback 或 delegate,则可以省略参数类型、返回类型。单语句闭包隐式返回其唯一语句。
let mappedNumbers = numbers.map({number in 3 * number })
print(mappedNumbers)
闭包体中可通过下标引用参数:
let sortedNumbers = numbers.sorted{$0 > $1}
print(sortedNumbers)
当闭包是函数的唯一参数时,可以省略小括号。
let sortedNumbers = numbers.sorted{$0 > $1}
print(sortedNumbers)
Objects and Classes
使用 class 关键字创建类。类的属性声明同常量和变量的声明一样,唯一区别属性声明在类中。同样方法和函数的声明写法一样。
class Shape {
var numberOfSides = 0
func simpleDescription() -> String {
return "A shape with\(numberOfSides) sides."
}
}
在类名后加 () 即可创建类的实例,使用 . 操作符访问属性和方法。
var shape = Shape()
shape.numberOfSides = 7
var shapeDescription = shape.simpleDescription()
使用 init 来初始化实例:
class NamedShape {
var numberOfSides: Int = 0
var name: String
init(name: String) {
self.name = name
}
func simpleDescription() -> String {
return "A shape with\(numberOfSides) sides."
}
}
使用 deinit 创建析构函数,当实例销毁时在析构函数中执行清理工作。
子类重载父类方法时需关键字 override 修饰,没有 override 编译器会报错。
class Square: NamedShape {
var sideLength: Double
init(sideLength: Double, name: String) {
self.sideLength = sideLength
super.init(name: name)
numberOfSides = 4
}
func area() -> Double {
return sideLength * sideLength
}
override func simpleDescription() -> String {
return "A square with sides of length \(sideLength)."
}
}
let test = Square(sideLength: 5.2, name: "my test square")
test.area()
test.simpleDescription()
日常使用中可以为属性添加 getter 和 setter 函数。
class EquilateralTriangle: NamedShape {
var sideLength: Double = 0.0
init(sideLength: Double, name: String) {
self.sideLength = sideLength
super.init(name: name)
numberOfSides = 3
}
var perimeter: Double {
get {
return 3.0 * sideLength
}
set {
sideLength = newValue / 3.0
}
}
override func simpleDescription() -> String {
return "An equilateral triangle with sides of length \(sideLength)."
}
}
var triangle = EquilateralTriangle(sideLength: 3.1, name: "a triangle")
print(triangle.perimeter)
triangle.perimeter = 9.9
print(triangle.sideLength)
在 perimeter 的 setter 函数中,新值有个隐式的名字 newValue,同样你可以在 set 之后显式的指定名字 set(newValue)。
EquilateralTriangle 的构造函数执行了三步:
- 初始化子类属性;
- 调用父类构造函数
- 初始化父类属性;
如需在设置新值前后执行自定义逻辑可使用 willSet 和 didSet。每当属性值发生变化,自定义逻辑都会被执行。
下例中 willSet 保证三角形的边长和正方形的边长始终相等。
class TriangleAndSquare {
var triangle: EquilateralTriangle {
willSet {
square.sideLength = newValue.sideLength
}
}
var square: Square {
willSet {
triangle.sideLength = newValue.sideLength
}
}
init(size: Double, name: String) {
square = Square(sideLength: size, name: name)
triangle = EquilateralTriangle(sideLength: size, name: name)
}
}
var triangleAndSquare = TriangleAndSquare(size: 10, name: "another test shape")
print(triangleAndSquare.square.sideLength)
print(triangleAndSquare.triangle.sideLength)
triangleAndSquare.square = Square(sideLength: 50, name: "larger square")
print(triangleAndSquare.triangle.sideLength)
使用 optional 值时,你可在执行任何操作(methods, properties 和 subscripting)之前添加 ?。如果 ? 之前的值为 nil,则 ? 之后的表达式都被忽略且整个表达式的值记为 nil。否则,optional 值会拆箱,? 之后的表达式作用在拆箱后的对象上。上述两种情况中,整个表达式的值都是 optional 的。
let optionalSquare: Square? = Square(sideLength: 2.5, name: "optional square")
let sideLength = optionalSquare?.sideLength
Enumerations and Structures
使用 enum 关键字创建枚举类型,与类以及其他 named types 一样,枚举类型也可拥有方法。
enum Rank: Int {
case ace = 1
case two, three, four, five, six, seven, eight, nine, ten
case jack, queen, king
func simpleDescription() -> String {
switch self {
case .ace:
return "ace"
case .jack:
return "jack"
case .queen:
return "queen"
case .king:
return "king"
default:
return String(self.rawValue)
}
}
}
let ace = Rank.ace
let aceRawValue = ace.rawValue
默认情况下,Swift 中的枚举是从 0 开始计数,并依次递增。你也可以显式指定初值,上例中 Ace 被显式指定 raw value 为 1,后续的枚举值依次递增。
枚举值也可使用字符串或浮点数,通过 rawValue 属性即可读取枚举的 raw value。
使用 init?(rawValue:) 构造函数从 raw value 实例化一个枚举实例。如果能找到匹配的 raw value 则返回相应 case,否则返回 nil。
if let convertedRank = Rank(rawValue: 3) {
let threeDescription = convertedRank.simpleDescription()
}
枚举的 case value 是实际值,并不是另一种形式的 raw values。如没有更有意义的 raw value,则没有必要提供。
enum Suit {
case spades, hearts, diamonds, clubs
func simpleDescription() -> String {
switch self {
case .spades:
return "spades"
case .hearts:
return "hearts"
case .diamonds:
return "diamonds"
case .clubs:
return "clubs"
}
}
}
let hearts = Suit.hearts
let heartsDescription = hearts.simpleDescription()
如果枚举有 raw values,则这些值在枚举声明时就已确定,这意味着每个特定枚举 case 的实例的值是一样的。另一种枚举 case 使用方法是 have values associated with the case - 这些值是在你定义实例时传入的且每个枚举实例其内部值是不同的。可以将这些 associated values 视为 enumeration case 实例的属性。
enum ServerResponse {
case result(String, String)
case failure(String)
}
let success = ServerResponse.result("6:00 am", "8:09 pm")
let failure = ServerResponse.failure("Out of cheese.")
switch success {
case let .result(sunrise, sunset):
print("Sunrise is at \(sunrise) and sunset is at \(sunset).")
case let .failure(message):
print("Failure... \(message)")
}
使用 struct 创建结构体,结构体与类一样可以定义属性、方法和构造函数。其和类最大的区别在于,在传递结构体时其采用值传递的方式,而类采用引用传递。
struct Card {
var rank: Rank
var suit: Suit
func simpleDescription() -> String {
return "The \(rank.simpleDescription()) of \(suit.simpleDescription())"
}
}
let threeOfSpades = Card(rank: .three, suit: .spades)
let threeOfSpadesDescription = threeOfSpades.simpleDescription()
Protocols and Extensions
使用 protocol 声明协议。
protocol ExampleProtocol {
var simpleDescription: String { get }
mutating func adjust()
}
类、枚举和结构体都可以实现协议:
class SimpleClass: ExampleProtocol {
var simpleDescription: String = "A very simple class."
var anotherProperty: Int = 69105
func adjust() {
simpleDescription += " Now 100% adjusted."
}
}
var a = SimpleClass()
a.adjust()
let aDescription = a.simpleDescription
struct SimpleStructure: ExampleProtocol {
var simpleDescription: String = "A simple structure"
mutating func adjust() {
simpleDescription += " (adjusted)"
}
}
var b = SimpleStructure()
b.adjust()
let bDescription = b.simpleDescription
SimpleStructure 定义中用到的 mutating 关键字标记该方法会修改结构体。SimpleClass 的声明不需要在方法声明中添加 mutating 标记,这是因为类中的方法通常都会修改类对象。
使用 extension 为已有类型添加新功能,比如新方法和 computed properties。你可以使用 extension 来为已有类型添加 protocol conformance,这些类型可以是定义在其他地方的,或者是从 library 或 framework 中导入的。
extension Int: ExampleProtocol {
var simpleDescription: String {
return "The number \(self)"
}
mutating func adjust() {
self += 42
}
}
print(7.simpleDescription)
定义好的 protocol 与其他 named type 一样 - for example, to create a collection of objects that have different types but that all conform to a single protocol.
let protocolValue: ExampleProtocol = a
print(protocolValue.simpleDescription)
// print(protocolValue.anotherProperty) // Uncomment to see the error
即使变量 protocolValue 的运行时类型为 SimpleClass,但编译器仍然把它视为 ExampleProtocol 类型,我们仅能访问协议中定义的属性和方法,而类中定义的其他属性和方法都不可访问。
Error Handling
Generics
参考文献: