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

Son*_*yen 5 dart flutter dart-null-safety

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

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

谢谢

jam*_*lin 30

我不是 Swift 方面的专家,但 Dart 会使用 null 检查来自动提升类型,我认为这主要完成if let和 的工作guard 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.
Run Code Online (Sandbox Code Playgroud)

请注意,不会对非局部变量或不同时是finalprivate 的变量执行提升,因此对于这些变量,您需要显式引入局部引用。

从 Dart 3 开始,您可以使用空检查模式来执行相同的操作,而无需将该局部变量引入外部作用域:

if (possiblyReturnsNull() case var x?) {
  // All code within this block treats `x` as non-nullable.
}

// `x` does not exist.
Run Code Online (Sandbox Code Playgroud)


Rog*_*ber 7

我将开始讨论这个问题,因为我也来自 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.
Run Code Online (Sandbox Code Playgroud)