1

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 Answers 2

5

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 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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much, that was very helpful :)
1

@Glorfindel answer with "A"..."Z" range is nice. You can also use NSRegularExpression to do so:

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
}

1 Comment

Thank you for your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.