Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
736 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...