我们可以在 SWIFT 中使用关键字作为参数名称吗? [英] Can we use keywords as parameter names in SWIFT?

查看:26
本文介绍了我们可以在 SWIFT 中使用关键字作为参数名称吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我想设置一个使用for"作为可读性参数的函数.

Basically, I want to set up a function that uses 'for' as a parameter for readability.

enum Genre {
    case drama
    case comedy
}

func setupTable(for: Genre) {
    switch for {
    case .drama: break
    case .comedy: break
    }
}

我设置了类似的东西,但是当我尝试使用for"的开关时,它作为关键字出现并引发编译错误.

I set something like this up but when i try and use the switch for 'for' it comes up as a keyword and throws a compile error.

干杯

推荐答案

当使用关键字作为普通标识符时,您必须像这样使用反引号 ` 将其转义

When using a keyword as a normal identifier you have to escape it using backticks ` like this

func setupTable(for: Genre) {
    switch `for` {
        case .drama: break
        case .comedy: break
    }
}


附带说明,正如@Hamish 在对该问题的评论中所指出的,您应该尽量避免将此类名称用于变量,这(在这种情况下)您可以通过为变量提供内部名称和外部名称来实现参数:


On a side note, as pointed out by @Hamish in a comment on the question, you should try to avoid using such names for variables, which (in this case) you can do by providing both an internal and external name for the parameter:

func setupTable(for genre: Genre) {
    switch genre {
        case .drama: break
        case .comedy: break
    }
}

这篇关于我们可以在 SWIFT 中使用关键字作为参数名称吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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