跳转到内容
Egrecho47's Blogen|zh
返回

Odd Expressions in Swift

更新于:

感觉 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.

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.

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.

@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.

@ViewBuilder
func buildView() -> some View {
    if condition {
        Text("Hello")
    } else {
        Text("World")
    }
}

分享这篇文章:

上一篇
扩展卢卡斯定理
下一篇
三件好事