Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using UIColor in a switch statement

I have an array of object in my first controller and I'm passing one to modify it by modal segue. This modal view is the same to create a new object and to fill it.

In the Storyboard of this modal I have 3 TextField and 5 buttons who represent color. When the user click on one I draw a border to mark it as selected.

When I load this modal view to modify my existing object I need to draw the border of the correct button.

I have a method who do that but it needs the UIButton instance in parameter. So I was wondering if it was possible to use a switch statement to know wich color is in my object and to call the function with the good UIButton instance.

    switch action?.color {
        case UIColor.redColor(): setBorderColor(rougeButton)
        case UIColor.blueColor(): setBorderColor(bleuButton)
        case UIColor.yellowColor(): setBorderColor(jauneButton)
        case UIColor.greenColor(): setBorderColor(vertButton)
        case UIColor.whiteColor(): setBorderColor(blancButton)
        default:
            setBorderColor(blancButton)
            action?.color = UIColor.whiteColor()
    }

Thansk in advance for your answer !

Edit :

I tried to print this color instance to see if I could transform it in other way to make the switch work.

println("\(action?.color)")

Which prints

Optional(UIDeviceWhiteColorSpace 1 1) // UIColor.whiteColor()
Optional(UIDeviceRGBColorSpace 1 0 0 1) // UIColor.redColor()

So I don't know what could I do because it returns different things

like image 545
dib258 Avatar asked Jan 01 '26 04:01

dib258


1 Answers

As is indicated by the output in your console, the 'color' property is an Optional. You need to EITHER:

  1. Find a way to avoid storing it as an optional
  2. Use Optional Chaining combined with Optional Binding before your switch statement:

    if let colorUnwrapped = action?.color {
    switch colorUnwrapped {
       //etc
    
like image 197
Craig Grummitt Avatar answered Jan 04 '26 12:01

Craig Grummitt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!