Nathan Rad
Nathan Rad

Reputation: 46

Can we use keywords as parameter names in SWIFT?

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
    }
}

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.

Cheers

Upvotes: 1

Views: 945

Answers (1)

Marco Boschi
Marco Boschi

Reputation: 2333

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
    }
}

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
    }
}

Upvotes: 5

Related Questions