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 | class Person { |
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 | func doSomething(completion: @escaping () -> Void) { |
@frozen
attribute can be used to mark a struct or enum that will not be extended in the future.
1 | @frozen enum Direction { |
@ViewBuilder
attribute can be used to mark a function so that it can simplify the process of building views.
1 |
|