[swift-evolution] Union instead of Optional

Cao Jiannan frogcjn at 163.com
Mon May 16 05:55:54 CDT 2016


Hi Austin,

let me repeat the example so that clarify my point from this example.

protocol cannot do this:

func input(value: ProtocolForABC) {
    print(value.someCommonProperty)

    if value is A {
        
    } else if value is B {
        
    } else if value is C {
        
    } else {
        // There no other cases, but compiler will not trigger a warning.
    }
}

The compiler will not know your protocol is only conformed to these three classes.
So the else block will not trigger a warning.

- Jiannan


> 在 2016年5月16日,18:37,Austin Zheng <austinzheng at gmail.com> 写道:
> 
> I'm sorry, but I don't understand the point you are trying to make.
> 
> If you pass in a value of type (A | B | C) to a function, what might you want to do with that value?
> 
> If you want to do one thing if the value is type A, something else if the value is type B, and something else if the value is type C, then you need to switch or otherwise type check the value at runtime. You can't get around this, no matter whether you use enums, protocols, generics, or union type.
> 
> If you want it to do something that A, B, and C all support, use a generic and/or a protocol. In this case limiting the inputs to only those three types is probably a design smell. The whole point of a shared interface is that it only matters that the interface is properly implemented by a type, not what that type is.
> 
> If you don't care about doing anything with the value, just make your function generic: func<T>(input: T).
> 
> Austin
> 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160516/3de15fab/attachment.html>


More information about the swift-evolution mailing list