Nico
Nico

Reputation: 6359

Can someone tell me if there is a syntax for what I would like to do in swift

I have a class like this one:

class Currency {
    let code: String
    let country: String
}

I have a segment control. When the 1st segment is pressed, I want the code, when the 2nd segment is pressed, I want the country

I'm checking it quite often in my code with:

self.segment.selectedSegmentIndex == 0 ? currency.country : currency.code

Is there a way to declare a constant with it like

let choice = self.segment.selectedSegmentIndex == 0 ? currency.country : currency.code

knowing that at the time of declaration, I haven't created currency yet and then, when I'm calling it, I could do for example

let char = first(currency.choice)

or something like it?

Thanks

Upvotes: 0

Views: 38

Answers (1)

mipadi
mipadi

Reputation: 410652

You could put it in a method or computed property. For a computed property, you could add this to whatever class contains the segment instance variable:

let choice: String {
    return segment.selectedSegmentIndex == 0 ? currency.country : currency.code
}

(This assumes that class also contains a currency instance variable.)

Upvotes: 2

Related Questions