更新时间:2022-11-24 07:37:30
popViewController(动画:)
返回 UIViewController?
,并且编译器正在发出警告,因为您没有捕获该值。解决方案是将它分配给下划线:
_ = navigationController?.popViewController(animated:true)
在Swift 3之前,默认情况下所有方法都有可丢弃的结果。当你没有捕获方法返回的内容时,不会发出警告。
为了告诉编译器应该捕获结果,你必须添加方法声明之前的@warn_unused_result
。它将用于具有可变形式的方法(例如 sort
和 sortInPlace
)。你可以添加 @warn_unused_result(mutable_variant =mutableMethodHere)
来告诉编译器。
但是, Swift 3,行为被翻转。现在所有方法都警告不会捕获返回值。如果您想告诉编译器不需要警告,请在方法声明之前添加 @discardableResult
。
如果您不想使用返回值,则必须显式通过将其分配给下划线来告诉编译器:
_ = someMethodThatReturnsSomething()
将此添加到Swift 3的动机:
sort
认为它修改了集合) UIKit API似乎落后于此,而不是添加 @discardableResult
以获得完全正常(如果不是更常见)的使用 popViewController(动画:)
而不捕获返回值。
I've got the following function which compiled cleanly previously but generates a warning with Xcode 8.
func exitViewController()
{
navigationController?.popViewController(animated: true)
}
"Expression of type "UIViewController?" is unused".
Why is it saying this and is there a way to remove it?
The code executes as expected.
popViewController(animated:)
returns UIViewController?
, and the compiler is giving that warning since you aren't capturing the value. The solution is to assign it to an underscore:
_ = navigationController?.popViewController(animated: true)
Before Swift 3, all methods had a "discardable result" by default. No warning would occur when you did not capture what the method returned.
In order to tell the compiler that the result should be captured, you had to add @warn_unused_result
before the method declaration. It would be used for methods that have a mutable form (ex. sort
and sortInPlace
). You would add @warn_unused_result(mutable_variant="mutableMethodHere")
to tell the compiler of it.
However, with Swift 3, the behavior is flipped. All methods now warn that the return value is not captured. If you want to tell the compiler that the warning isn't necessary, you add @discardableResult
before the method declaration.
If you don't want to use the return value, you have to explicitly tell the compiler by assigning it to an underscore:
_ = someMethodThatReturnsSomething()
Motivation for adding this to Swift 3:
sort
thinking it modifies the collection)The UIKit API appears to be behind on this, not adding @discardableResult
for the perfectly normal (if not more common) use of popViewController(animated:)
without capturing the return value.