Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 2: expression pattern of type 'Bool' cannot match values of type 'Int'

I'm doing this problem set "FizzBuzz", and my switch statement is giving me some problems, here's my code:

func fizzBuzz(n: Int) -> String {   
    switch n {
    case n % 3 == 0: print("Fizz")
    case n % 5 == 0: print("Buzz")
    case n % 15 == 0:print("FizzBuzz")
    }
    return "\(n)"
}

If you could provide me with pointers / hints, instead of giving me the correct code, that would be swell :D I'd prefer solving it myself, but a few hints could get me out of this hole.

like image 920
user3724487 Avatar asked Nov 28 '15 19:11

user3724487


2 Answers

Just two things wrong:

(1) Your cases are boolean expressions, so you want to compare them against true, not n;

(2) You need a default case. So:

func fizzBuzz(n: Int) -> String {
    switch true {
    case n % 3 == 0: print("Fizz")
    case n % 5 == 0: print("Buzz")
    case n % 15 == 0: print("FizzBuzz")
    default: print("Shoot")
    }
    return "\(n)"
}
like image 65
matt Avatar answered Oct 18 '22 11:10

matt


You can use case let where and check if both match before checking them individually:

func fizzBuzz(n: Int) -> String {
    let result: String
    switch n {
    case let n where n.isMultiple(of: 3) && n.isMultiple(of: 5):
        result = "FizzBuzz"
    case let n where n.isMultiple(of: 3):
        result = "Fizz"
            case let n where n.isMultiple(of: 5):
        result = "Buzz"
    default:
        result = "none"
    }
    print("n:", n, "result:", result)
    return result
}
like image 26
Leo Dabus Avatar answered Oct 18 '22 11:10

Leo Dabus