squarehippo10 squarehippo10 - 4 months ago 24
Swift Question

Swift refactoring assistance

I have a meter laid out on a storyboard that is comprised of ten segments. There are an additional ten segments on top of the original segments that are colored to simulate a lighted segment - these are outlets. (See image below.) Currently I am using a switch statement to hide and unhide each outlet/segment based on a constantly varying input level. But, as you can see in the code below, it's not pretty. I keep reading that polymorphism is often the way to improve a switch statement, but I can't see how that would help here.

switch input {
case 0...9:
seg1.hidden = false
seg2.hidden = true
seg3.hidden = true
seg4.hidden = true
seg5.hidden = true
seg6.hidden = true
seg7.hidden = true
seg8.hidden = true
seg9.hidden = true
seg10.hidden = true
case 10...19:
seg1.hidden = false
seg2.hidden = false
seg3.hidden = true
seg4.hidden = true
seg5.hidden = true
seg6.hidden = true
seg7.hidden = true
seg8.hidden = true
seg9.hidden = true
seg10.hidden = true
...
and on and on for eight more levels.


enter image description here

Answer
//You can have these segments in an array like this-

let segments = [seg1, seg2, seg3, seg4, seg5,seg6, seg7, seg8, seg9, seg10]

// Function that will setup the segments based on input

func setUpSegmentsForInputValue(segments:[UIView], value:Int) {
    for (index, segment) in segments.enumerate() {
        segment.hidden = (value/10)  != index
    }
}

// Call the function with whatever input values 
setUpSegmentsForInputValue(segments: segments, value: someValue)
Comments