When did `guard let foo = foo` become legal?

前端 未结 1 556
滥情空心
滥情空心 2020-12-06 11:35

Back in November of 2016 I posted a question asking why I couldn\'t use guard to create an unwrapped version of a variable using the same name as the optional, like you can

相关标签:
1条回答
  • 2020-12-06 12:28

    TL;DR

    guard let foo = foo is legal if foo was defined in another scope.


    The example from your linked question:

    func test()
    {
      let a: Int? = 1
    
      guard let a = a else{
        return
      }
      print("a = \(a)")
    }
    

    still doesn't work because the guard statement is trying to create another variable a in the same scope.

    This example:

    //Test of using guard to create an unwrapped version of a var, like if let
    func guardTest(_ viewController: UIViewController?) -> UIViewController? {
      // Check if the current viewController exists
      print(String(describing: viewController))
      guard let viewController = viewController else {
        return nil
      }
      print(String(describing: viewController))
    
      return viewController
    }
    

    works for the same reason that this does:

    func test(a: Int)
    {
        print(type(of: a))  // Int
    
        let a = 3.14
    
        print(type(of: a))  // Double
    }
    

    The parameter to the function is defined in a different scope, so Swift allows you to create a local variable with the same name.

    0 讨论(0)
提交回复
热议问题