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

查看:90
本文介绍了Swift 2:“布尔"类型的表达式模式不能与"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 % 3 == 0 && n % 5 == 0:
        result = "FizzBuzz"
    case let n where n % 3 == 0:
        result = "Fizz"
    case let n where n % 5 == 0:
        result = "Buzz"
    default:
        result = "none"
    }
    print("n:", n, "result:", result)
    return result
}

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

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