Odd Expressions in Swift

03 / 29 / 2023 | 最后修改于 05 / 24 / 2023

感觉 Swift 的奇怪语法糖或者说特性简直,,,惊为天人,混乱不堪还挺方便的。

Key-Path Expressions

The Key-Path Expressions in Swift is a very useful feature. It can be used to access the properties of a class or struct. For example, we can use the key-path expression to access the name property of a Person class.

1
2
3
4
5
6
7
8
9
10
class Person {
var name: String
init(name: String) {
self.name = name
}
}

let person = Person(name: "John")
let nameKeyPath = \Person.name
print(person[keyPath: nameKeyPath])

Note that the key-path expression is processed in the compile time, so it is very efficient.(But also means that it can’t be used to access the dynamic properties and can’t be changed at runtime.)

Attribute

At first, I mistook the attribute as wrapper.(Because I saw the @ symbol.)

While actually it’s used to add some metadata to the class, struct, enum, property, method, etc.

Here are some examples.

@escaping attribute can be used to mark a closure that will be stored outside the scope of the function.

1
2
3
4
5
func doSomething(completion: @escaping () -> Void) {
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
completion()
}
}

@frozen attribute can be used to mark a struct or enum that will not be extended in the future.

1
2
3
4
5
6
@frozen enum Direction {
case north
case south
case east
case west
}

@ViewBuilder attribute can be used to mark a function so that it can simplify the process of building views.

1
2
3
4
5
6
7
8
@ViewBuilder
func buildView() -> some View {
if condition {
Text("Hello")
} else {
Text("World")
}
}