Swift 2:“Bool"类型的表达式模式不能匹配“Int"类型的值 [英] Swift 2: expression pattern of type 'Bool' cannot match values of type 'Int'

查看:20
本文介绍了Swift 2:“Bool"类型的表达式模式不能匹配“Int"类型的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做这个问题集FizzBu​​zz",我的 switch 语句给了我一些问题,这是我的代码:

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)"
}

如果你能给我提供指针/提示,而不是给我正确的代码,那就太好了:D我更愿意自己解决它,但一些提示可以让我摆脱这个困境.

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.

推荐答案

您可以使用 case let where 并在单独检查它们之前检查两者是否匹配:

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
}

这篇关于Swift 2:“Bool"类型的表达式模式不能匹配“Int"类型的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆