2017-02-16 29 views
0

我可以在这里匹配什么来使这个测试通过?如何在Swift switch语句中匹配可选<*> .none?

func testMatchNone() { 
    let none: String? = nil 
    let foo: Any = none 

    switch foo { 
    case nil: 
     break 

    default: 
     XCTFail() 
    } 
} 

试图Optional.none编译器会抱怨它不知道什么泛型类型可选的是,这是公平的。但我不在乎,我只是想匹配,如果它是任何泛型类型的nil/.none

回答

0

算出来:

func testMatchNone() { 
    let none: String? = nil 
    let foo: Any = none 

    switch foo { 
    case Optional<Any>.none: 
     break 

    default: 
     XCTFail() 
    } 
} 
+0

为什么不'案例零:'? – Alexander

+0

亲自运行,看看它是否有效。 –

+0

它编译,但不像预期的那样。 '可选.none'工作,但 – Alexander