Swift中被忽略的参数的用例是什么 [英] What is the usecase for ignored parameters in Swift

查看:77
本文介绍了Swift中被忽略的参数的用例是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Swift中,您可以编写以下内容:

In Swift, you can write the following:

func foo(_:Int) -> { return 1 }

下划线是忽略的参数.我只是因为文档而知道这一点,但无法想到为什么还要这样做的任何用例.我想念什么吗?

Where the underscore is an ignored parameter. I only know this because of the documentation, but cannot think of ANY usecase on why you would even do this. Am I missing something?

推荐答案

在以下情况下,忽略参数(或元组的成员,它们非常接近同一事物)很有意义.

Ignoring parameters (or members of a tuple, which are pretty close to the same thing) makes sense when:

  • 您要重写超类函数或实现协议定义的函数,但是该函数的实现不需要参数之一.例如,如果您挂起了应用程序启动但不需要在该方法中引用共享的UIApplication实例:

override func application(_: UIApplication!, didFinishLaunchingWithOptions _: NSDictionary!) -> Bool { /* ... */ }

  • 您正在提供闭包(ObjC中的aka块)作为某些API的参数,但是使用该API并不关心闭包的参数之一.例如,如果您要向照​​片库提交更改,并且想引起注意,则可以忽略完成处理程序中的successerror参数:

  • You're providing a closure (aka block in ObjC) as a parameter to some API, but your use of that API doesn't care about one of the parameters to the closure. For example, if you're submitting changes to the Photos library and want to throw caution to the wind, you can ignore the success and error parameters in the completion handler:

    PHPhotoLibrary.sharedPhotoLibrary().performChanges({
        // change requests
    }, completionHandler: { _, _ in
        NSLog("Changes complete. Did they succeed? Who knows!")
    })
    

  • 您正在调用的函数/方法提供了多个返回值,但不在乎其中一个.例如,假设一个假设的NSColor方法将组件作为一个元组返回,则可以忽略alpha:

  • You're calling a function/method that provides multiple return values, but don't care about one of them. For example, assuming a hypothetical NSColor method that returned components as a tuple, you could ignore alpha:

    let (r, g, b, _) = color.getComponents()
    

  • 其背后的原因是它使您的代码更具可读性.如果为不使用的参数(或元组成员)声明一个本地名称,则其他正在读取代码的人(很可能只是您几个月后的版本)可能会看到该名称并感到疑惑在函数体中的何处或如何使用它.如果预先声明要忽略该参数(或元组成员),那么很明显,无需在该范围内担心它. (理论上,这也可以为编译器提供优化提示,这也可能使您的代码运行得更快.)

    The reasoning behind this is that it makes your code more readable. If you declare a local name for a parameter (or tuple member) that you don't end up using, someone else reading your code (who could well be just the several-months-later version of yourself) might see that name and wonder where or how it gets used in the function body. If you declare upfront that you're ignoring that parameter (or tuple member), it makes it clear that there's no need to worry about it in that scope. (In theory, this could also provide an optimization hint to the complier, which might make your code run faster, too.)

    这篇关于Swift中被忽略的参数的用例是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆