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

回眸只為那壹抹淺笑 提交于 2019-11-27 23:56: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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!