如何避免在Swift中写入“变量j,但从不读取”?

时间:2023-01-23 22:19:18

I am using variable j to print its final value inside a defer block as shown below:

我正在使用变量j在一个延迟块中打印它的最终值,如下所示:

func justForFun()
{    
   defer {let x = j; print("\(x)")}
   var j = 0
   for i in 1...5
   {
       print("\(i)")
       j = i*2;
   }
}
justForFun()

So, the variable j is indeed read and printed inside the defer block. Still, PlayGround displays the warning that variable j is written, but never read. Is there a way to enlighten the compiler and to rid this warning?

因此,变量j确实被读取并打印在延迟块中。然而,游乐场仍然显示了变量j被写入的警告,但是永远不会读取。有什么方法可以启发编译器并消除这个警告吗?

2 个解决方案

#1


1  

The warning disappears if the variable declaration is moved above the defer.

如果变量声明移动到延迟之上,则警告将消失。

$ cat d.swift 
func justForFun() {    
   var j = 0
   defer {let x = j; print("\(x)")}
   for i in 1...5 {
       print("\(i)")
       j = i*2;
   }
}
justForFun()

$ swift d.swift 
1 
2
3
4
5
10

While this doesn't explain why the warning appears, it does answer how you can make the warning go away.

虽然这并不能解释为什么会出现警告,但它确实可以回答如何使警告消失。

As far as enlightening the compiler, I don't think you can do that. You might want to file and issue at swift.org; see this page for how to report a bug. It seems the static flow checker is not looking at defer statements, which I believe it should. Good find.

至于启发编译器,我认为你做不到。您可能想要在swift.org上提交和发布文件;有关如何报告错误,请参阅此页。看起来静态流检查器没有查看延迟语句,我认为应该这样做。好找。

#2


0  

Workaround

Adding an anonymous assignment, _ =, eliminates the warning:

添加一个匿名赋值,_ =,消除警告:

// Swift 3.0
func justForFun()
{
  defer {let x = j; print("\(x)")}
  var j = 0

  // anonymous assignment:
  _ = j
  for i in 1...5
  {
    print("\(i)")
    j = i*2;
  }
}

justForFun()

#1


1  

The warning disappears if the variable declaration is moved above the defer.

如果变量声明移动到延迟之上,则警告将消失。

$ cat d.swift 
func justForFun() {    
   var j = 0
   defer {let x = j; print("\(x)")}
   for i in 1...5 {
       print("\(i)")
       j = i*2;
   }
}
justForFun()

$ swift d.swift 
1 
2
3
4
5
10

While this doesn't explain why the warning appears, it does answer how you can make the warning go away.

虽然这并不能解释为什么会出现警告,但它确实可以回答如何使警告消失。

As far as enlightening the compiler, I don't think you can do that. You might want to file and issue at swift.org; see this page for how to report a bug. It seems the static flow checker is not looking at defer statements, which I believe it should. Good find.

至于启发编译器,我认为你做不到。您可能想要在swift.org上提交和发布文件;有关如何报告错误,请参阅此页。看起来静态流检查器没有查看延迟语句,我认为应该这样做。好找。

#2


0  

Workaround

Adding an anonymous assignment, _ =, eliminates the warning:

添加一个匿名赋值,_ =,消除警告:

// Swift 3.0
func justForFun()
{
  defer {let x = j; print("\(x)")}
  var j = 0

  // anonymous assignment:
  _ = j
  for i in 1...5
  {
    print("\(i)")
    j = i*2;
  }
}

justForFun()