【问题标题】:Equivalent of if let and guard let of Swift in Dart相当于 Dart 中 Swift 的 if let 和 guard let
【发布时间】:2021-05-02 08:41:48
【问题描述】:

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

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

谢谢

【问题讨论】:

    标签: flutter dart dart-null-safety


    【解决方案1】:

    在 Dart 中检查 null 安全性:

    value ?? 0
    

    【讨论】:

    • 不,我的意思是if let 在代码块中有一个新的非空值,而guard let 是函数体其余部分的非空值。我们可以在 Dart 中检查该值是否为 null,但是在代码中,它仍然被视为可为 null。
    • value || 0 毫无意义,甚至不是合法的 Dart。
    • 对不起,这是一个错字,它的双问号
    【解决方案2】:

    我不是 Swift 专家,但 Dart 会使用 null 检查来自动提升类型,我认为这主要完成了 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 提供了一种机制,允许更好的机制添加本地引用而不污染外部范围。)

    【讨论】:

    • 非本地的事情解释说,我想知道为什么在某些情况下它有效而有些无效。谢谢
    【解决方案3】:

    我要加入这个话题,因为我也来自 Swift,并且非常喜欢使用后卫。再加上@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.
    

    【讨论】:

      【解决方案4】:

      对已接受答案的一个小扩展是,Flutter 还允许强制展开 Optional。因此,如果您正在访问未保存在变量中的非零值,例如在字典中,您需要在 if 语句中解开它:

      if (someDict[someKey] != null) {
        print(someDict[someKey]!)
      }
      //
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-08
        • 1970-01-01
        • 2019-11-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多