本文主要介绍一下Swift中一些常见的语法糖

Function 相关

Functions With an Implicit Return

  • Functions With an Implicit Return 具有隐式返回的函数
  • 如果函数的整个主体是单个表达式,则函数会隐式返回该表达式。例如,以下两个函数具有相同的行为:
  • swift Functions官方文档
1
2
3
4
5
6
7
8
9
10
11
12
func greeting(for person: String) -> String {
"Hello, " + person + "!"
}
print(greeting(for: "Dave"))
// "Hello, Dave!"


func test() -> Int {
1 + 2
}
print(test())
// 8

计算属性(Computed Properties) 相关

swift Computed Properties官方文档

  • 除了存储属性之外,类、结构和枚举还可以定义计算属性,它们实际上并不存储值。相反,它们提供了一个 getter 和一个可选的 setter 来间接检索和设置其他属性和值。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
struct Point {
var x = 0.0, y = 0.0
}
struct Size {
var width = 0.0, height = 0.0
}
struct Rect {
var origin = Point()
var size = Size()
var center: Point {
get {
let centerX = origin.x + (size.width / 2)
let centerY = origin.y + (size.height / 2)
return Point(x: centerX, y: centerY)
}
set(newCenter) {
origin.x = newCenter.x - (size.width / 2)
origin.y = newCenter.y - (size.height / 2)
}
}
}

var square = Rect(origin: Point(x: 0.0, y: 0.0),
size: Size(width: 10.0, height: 10.0))
let initialSquareCenter = square.center
// initialSquareCenter is at (5.0, 5.0)
print("square.origin is now at (\(square.origin.x), \(square.origin.y))")
// Prints "square.origin is now at (10.0, 10.0)"

Shorthand Getter Declaration

  • 简略的 Getter 声明
  • 如果 getter 的整个主体是单个表达式,则 getter 会隐式返回该表达式。这是结构的另一个版本Rect,它利用了这种简写符号和 setter 的简写符号:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
struct CompactRect {
var origin = Point()
var size = Size()
var center: Point {
get {
Point(x: origin.x + (size.width / 2),
y: origin.y + (size.height / 2))
}
set {
origin.x = newValue.x - (size.width / 2)
origin.y = newValue.y - (size.height / 2)
}
}
}
// Getter 中省略 return 的规则和 Funciton 中的规则相同

Read-Only Computed Properties

  • 只读的计算属性
  • 具有 getter 但没有 setter 的计算属性称为只读计算属性。只读计算属性总是返回一个值,并且可以通过点语法访问,但不能设置为不同的值。
1
2
3
4
5
6
7
8
9
struct Cuboid {
var width = 0.0, height = 0.0, depth = 0.0
var volume: Double { // 只读 Read-Only
return width * height * depth
}
}
let fourByFiveByTwo = Cuboid(width: 4.0, height: 5.0, depth: 2.0)
print("the volume of fourByFiveByTwo is \(fourByFiveByTwo.volume)")
// Prints "the volume of fourByFiveByTwo is 40.0"

由上面的 省略 getter 中的 return 可知, 下面的写法依然正确

1
2
3
4
5
6
7
8
9
struct Cuboid {
var width = 0.0, height = 0.0, depth = 0.0
var volume: Double { // 只读 Read-Only
width * height * depth // 隐式return
}
}
let fourByFiveByTwo = Cuboid(width: 4.0, height: 5.0, depth: 2.0)
print("the volume of fourByFiveByTwo is \(fourByFiveByTwo.volume)")
// Prints "the volume of fourByFiveByTwo is 40.0"

隐式 return 虽然能省略一个关键字,但是总感觉怪怪的,个人并不推荐这么写~