【问题标题】:Swift: How to use for-in loop with an optional?Swift:如何将 for-in 循环与可选参数一起使用?
【发布时间】:2015-12-17 10:37:36
【问题描述】:

将 for-in 循环与可选项一起使用的正确方法是什么?

现在我总是在循环之前执行一个可选绑定。还有其他成语吗?

let optionalInt:[Int]? = [1, 2, 3]

if let optionalInt = optionalInt {
  for i in optionalInt {
    print(i)
  }
}

【问题讨论】:

    标签: swift2 optional for-in-loop


    【解决方案1】:

    如果要对数组的所有元素应用一组操作,可以用forEach{}闭包替换for循环并使用optional chaining

    var arr: [Int]? = [1, 2, 3]
    arr?.forEach{print($0)}
    

    【讨论】:

    • 不,这不是唯一的答案。但是,它是最短的。
    • 请注意,您不能在 forEach 上中断。
    • 请注意,如果循环是对象初始化逻辑的一部分,则不能执行 forEach,因为在 self 初始化之前,闭包无法捕获 self。
    • 这也增加了不必要的内存和性能占用
    • 内存和性能占用即使不相似也相同。如果您想减少内存占用,请考虑在 for 循环中使用 autoreleasepool:developer.apple.com/library/archive/documentation/Cocoa/…
    【解决方案2】:

    我认为没有合适的方法。有很多不同的方法,这真的取决于你喜欢什么,Swift 充满了可以根据你的选择让你的程序看起来非常漂亮的功能。

    以下是我能想到的一些方法:

    let optionalInt:[Int]? = [1, 2, 3]
    
    for i in optionalInt! { print(i) }
    
    for i in optionalInt ?? [] { print(i) }
    
    for i in optionalInt as [Int]! {  print(i) }
    

    【讨论】:

      【解决方案3】:

      你可以这样写:

      let optionalInt:[Int]? = [1, 2, 3]
      for i in optionalInt ?? [Int]() {
          print(i)
      }
      

      但我建议你避免使用可选值,例如你可以这样写:

      var values = [Int]()
      // now you may set or may not set 
      for i in values {
          print(i)
      }
      

      或者如果你想使用可选值并且函数中的这段代码调用可以使用guard

      guard let values = optionalInt else { return }
      for i in values {
          print(i)
      }
      

      【讨论】:

        【解决方案4】:

        最干净的解决方案有时是最基本的解决方案

        if let a = myOptionalArray {
            for i in a {
                
            }
        }
        

        所以我建议,保持你的方法

        上面的方法只插入一个空选项,或者forEach创建一个块只是因为if let a = optional {不够性感

        【讨论】:

          【解决方案5】:

          我迟到了两年,但我认为这是最好的方法。

          func maybe<T>(risk: T?, backup: T) -> T {
            return risk.maybe(backup)
          }
          

          extension Optional {
             func maybe(_ backup: Wrapped) -> Wrapped {
               switch self {
               case let .some(val):
                  return val
               case .none:
                  return backup
               }
             }
          }
          

          现在

          for i in optionalInt.maybe([]) {
              print(i)
          }
          

          【讨论】:

          • 哈哈? `for i in optionalInt ?? [] { print(i) }'
          • 哈!用佳能杀死蚊子
          • wau,我有时只是想,objective-c nil 行为有什么问题?我们又回到了如何循环简单数组而不是编写样板文件......啊我忘了,swift设计师只需要与众不同哈哈
          • 有多少人挠了挠头才意识到这是个玩笑?
          猜你喜欢
          • 1970-01-01
          • 2023-03-27
          • 1970-01-01
          • 1970-01-01
          • 2017-05-21
          • 2012-06-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多