高级模式匹配swift

时间:2017-04-24 15:52:34

标签: swift switch-statement pattern-matching

有没有办法在switch-case分支机构中使用选项? 例如:某些函数f(arg:)返回String?。 当switch-case返回非零值时,我们需要执行一些f(arg:)分支,并使用此值。请参阅以下示例。

func f(arg: Int) -> String?

let someValue: Int = ...

switch someValue {
    case -3, -2, -1:
        print("error: negative")
    case 10, 11, 12:
        print("error: too big")
    case let value, let str = f(arg: value): // HOW ????
        print("success: non-nil string \(str)")
    default:
        print("fail")    
}

2 个答案:

答案 0 :(得分:1)

I think your switch statement is equivalent to this:

switch someValue {
    case -3, -2, -1:
        print("error: negative")
    case 10, 11, 12:
        print("error: too big")
    default:
        if let str = f(arg: someValue) {
            print("success: non-nil string \(str)")
        } else {
            print("fail")
        }
}

But a cleaner way to write that would be using a guard statement so you know that someValue is valid before passing it to the function:

guard case 0...9 = someValue else {
    print("someValue is outside of valid range")
    // Handle error
    return
}

if let str = f(arg: someValue) {
    print("success: non-nil string \(str)")
} else {
    print("fail")
}

Another alternative is to simply make f returns nil if the argument is not in the expected range:

func f(arg: Int) -> String? {
    guard case 0...9 = arg else {
        print("\(arg) is not in the valid range of 0...9")
        return nil
    }

    // ...
}

if let str = f(arg: someValue) {
    print("success: non-nil string \(str)")
} else {
    print("fail")
}

答案 1 :(得分:0)

旧的,但这可能是你想要的:

func f(arg: Int) -> String?

let someValue: Int = ...

switch (someValue, f(arg: value)) {
    case (-3 ... -1, _):
        print("error: negative")
    case (10...12, _):
        print("error: too big")
    case (_, let str?):
        print("success: non-nil string \(str)")
    default:
        print("fail")    
}