相当于 Dart 中 Swift 的 if let 和 guard let

时间:2021-01-28 12:44:25

标签: flutter dart dart-null-safety

刚开始使用原生 iOS 背景的 Flutter,所以我有一个关于 Dart beta null 安全性的快速问题。

所以在 Swift 中,因为他们和 Kotlin 一样从一开始就有空安全的想法,所以我非常喜欢该语言的两个特性是 if letguard let。这两个使使用可选值变得更加容易。我不确定 Dart 的测试版是否有类似的东西。

谢谢

3 个答案:

答案 0 :(得分:3)

我不是 Swift 专家,但 Dart 会使用空检查来自动提升类型,我认为这主要完成了 if letguard let 的工作。

例如:

String? x = possiblyReturnsNull();
if (x != null) {
  // All code within this block treats `x` as non-nullable.
}
// All code outside the block continues to treat `x` as nullable.

注意 that promotion won't be performed on non-local variables,因此对于那些您需要明确引入本地引用的人。 (There is a language proposal 提供一种机制,允许更好的机制添加本地引用而不污染外部作用域。)

答案 1 :(得分:1)

我将继续讨论这个问题,因为我也来自 Swift 并且非常喜欢使用guard。加上@jamesdlin 所说的,反之亦然。

因此您可以在功能上执行 Swift 防护语句:

String? x = possiblyReturnsNull();
if (x == null) return whatever; // This works like Swift's guard
// All code outside the block now treats `x` as NON-nullable.

答案 2 :(得分:-1)

在 Dart 中检查空值安全性:

value ?? 0