Swift重构帮助

时间:2016-04-27 03:07:44

标签: swift refactoring

我的故事板上有一个由十个部分组成的仪表。在原始段的顶部还有十个段,这些段被着色以模拟发光段 - 这些段是出口。 (见下图。)目前我正在使用switch语句根据不断变化的输入级别隐藏和取消隐藏每个插座/段。但是,正如您在下面的代码中看到的那样,它并不漂亮。我一直在读,多态性通常是改进switch语句的方法,但是我看不出这会有什么帮助。

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

2 个答案:

答案 0 :(得分:2)

//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)

答案 1 :(得分:1)

您可以将所有插座添加到阵列中。将输入映射到"索引范围"如果出口处于"索引范围"则在for循环中决定。然后相应地设置隐藏属性。

@IBOutlet weak var seg1 = UIView()
@IBOutlet weak var seg2 = UIView()
@IBOutlet weak var seg3 = UIView()
@IBOutlet weak var seg4 = UIView()

...

let segs = [seg1, seg2, seg3, seg4]

let input = 19
let range = 0 ... input / 10

for (index, seg) in segs.enumerate() {
    if range ~= index {
        seg.hidden = false
    }else {
        seg.hidden = true
    }
}

替代(而不是for循环):

@IBOutlet weak var seg1 = UIView()
@IBOutlet weak var seg2 = UIView()
@IBOutlet weak var seg3 = UIView()
@IBOutlet weak var seg4 = UIView()

...

let segs = [seg1, seg2, seg3, seg4]

let input = 19
let range = 0 ... input / 10

segs.enumerate().forEach { index, seg in
    seg.hidden = !(range ~= index)
}

希望这有帮助。