[英]xcode- Refactoring switch with several cases.
So basically I want to create a keyboard and when the user click on a letter something should happen: 所以基本上我想创建一个键盘,当用户单击一个字母时,应该会发生一些事情:
@IBAction func letterBtn(sender: UIButton) { // All the letter buttons are linked to this func.
switch sender.currentTitle! {
case "A":
moveLetters(sender)
case "B":
moveLetters(sender)
case "C":
moveLetters(sender)
case "D":
moveLetters(sender)
case "E":
moveLetters(sender)
case "F":
moveLetters(sender)
case "G":
moveLetters(sender)
default :
println("Error")
}
}
func animateLetter (pos: UILabel, btn: UIButton) { // Make the letter move towards a label.
UIView.animateWithDuration(0.5, animations: { () -> Void in
btn.center = pos.center
})
}
func moveLetters (btn: UIButton) { // Determine which label the pressed letter should move towards.
switch emptyPos.count {
case 1:
animateLetter(pos1, btn: btn)
emptyPos.append(0)
case 2:
animateLetter(pos2, btn: btn)
emptyPos.append(0)
case 3:
animateLetter(pos3, btn: btn)
emptyPos.append(0)
case 4:
animateLetter(pos4, btn: btn)
emptyPos.append(0)
default:
println("Error")
}
}
I found myself using multiple switch cases that basically do the same thing in 2 different functions, and I was wondering if there a better way than using 26 cases for the entire alphabet, and also for my other function. 我发现自己使用了多个开关盒,这些开关盒在2个不同的功能上基本上可以完成相同的工作,我想知道是否有比对整个字母表以及其他功能使用26个盒更好的方法。
First of all, you can combine cases: 首先,可以合并各种情况:
switch sender.currentTitle! {
case "A", "B", "C": ... etc
// do something
Second, the switch statement allows intervals , from which you could profit by looking at the first character of the button title: 其次,switch语句允许使用interval ,您可以通过查看按钮标题的第一个字符来获利:
switch sender.currentTitle![0] {
case "A"..."Z":
// do something
}
As for your other question, I'd give each label a tag (pos1.tag = 1, pos2.tag = 2) etc. and use the viewWithTag function to get the right label. 至于您的其他问题,我会给每个标签一个标签(pos1.tag = 1,pos2.tag = 2)等,然后使用viewWithTag函数来获取正确的标签。
@Glorfindel answer with "A"..."Z"
range is nice. @Glorfindel答案为
"A"..."Z"
范围很好。 You can also use NSRegularExpression
to do so: 您还可以使用
NSRegularExpression
这样做:
let regex = try! NSRegularExpression(pattern: "^[A-Z]", options: .CaseInsensitive)
let range = NSMakeRange(0, distance(str.startIndex, str.endIndex))
if let match = regex.firstMatchInString(str, options: .ReportCompletion, range: range) {
// Do something
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.