Xcode 8 / Swift 3:“UIViewControllertypes的expression式? 未使用“警告
我已经得到了以前编译干净的函数,但用Xcode 8生成警告。
func exitViewController() { navigationController?.popViewController(animated: true) }
“UIViewControllertypes的expression式”未被使用“。
为什么说这个,有没有办法将其删除?
代码按预期执行。
TL; DR
popViewController(animated:)返回UIViewController? ,并且编译器正在给出这个警告,因为你没有捕获这个值。 解决scheme是将其分配给下划线:
_ = navigationController?.popViewController(animated: true)
Swift 3变化
在Swift 3之前,所有的方法默认都有一个“可丢弃的结果”。 当你没有捕获什么方法返回时,不会发生警告。
为了告诉编译器应该捕获结果,你必须在方法声明之前添加@warn_unused_result 。 它将用于具有可变forms的方法(例如sort和sortInPlace )。 你会添加@warn_unused_result(mutable_variant="mutableMethodHere")告诉编译器。
但是,在Swift 3中,行为被翻转了。 现在所有的方法都会警告返回值没有被捕获。 如果你想告诉编译器这个警告是不必要的,你可以在方法声明前添加@discardableResult 。
如果您不想使用返回值,则必须通过将其分配给下划线来明确告诉编译器:
_ = someMethodThatReturnsSomething()
将这个添加到Swift 3的动机:
- 预防可能的错误(例如使用
sort思路修改集合) - 明确的意图不捕获或需要捕获其他合作者的结果
UIKit API似乎是在这个背后,没有添加@discardableResult完全正常(如果不是更常见的话)使用popViewController(animated:)而不捕获返回值。
阅读更多
- SE-0047斯威夫特演变提议
- 接受提案与修订
当生活给你柠檬,延长:
import UIKit extension UINavigationController { func pop(animated: Bool) { _ = self.popViewController(animated: animated) } func popToRoot(animated: Bool) { _ = self.popToRootViewController(animated: animated) } }
请注意 ,添加类似@discardableResult func pop(animated: Bool) -> UIViewController? 会导致你试图避免的警告。
有了扩展,你现在可以写:
func exitViewController() { navigationController?.pop(animated: true) } func popToTheRootOfNav() { navigationController?.popToRoot(animated: true) }
编辑:也添加popToRoot。
在Swift 3中,忽略具有声明的返回值的函数的返回值会导致警告。
一种select退出的方法是使用@discardableResult属性标记该函数。 由于您无法控制此function,因此无法使用。
另一种摆脱警告的方法是将值赋给_ 。 这告诉编译器你知道该方法返回一个值,但你不想保留在内存中。
let _ = navigationController?.popViewController(animated: true)
work correctly if kept as it is但number of warning increases.的number of warning increases.但它work correctly if kept as it is number of warning increases.
解决方法是简单地replace it with underscore ( _ )尽pipe它看起来很丑。
Eg. _ = navigationController?.popViewController(animated: true)
另一种方法是你可以解开self.navigationController? 值并调用popViewController函数。
if let navigationController = navigationController { navigationController.popViewController(animated: true) }