Determine if Any.Type is Optional

前端 未结 4 1679
滥情空心
滥情空心 2020-12-05 19:55

I’m trying to determine if a given type t (Any.Type) is an optional type, I’m using this test

t is Optional.Type
         


        
4条回答
  •  悲哀的现实
    2020-12-05 20:12

    Assuming that what you are trying to do is something like this:

    let anyType: Any.Type = Optional.self
    anyType is Optional.Type // false
    

    Sadly swift currently (as of Swift 2) does not support covariance nor contravariance and type checks directly against Optional.Type cannot be done:

    // Argument for generic parameter 'Wrapped' could not be inferred
    anyType is Optional.Type // Causes error
    

    An alternative is to make Optional extend an specific protocol, and check for that type:

    protocol OptionalProtocol {}
    
    extension Optional : OptionalProtocol {}
    
    let anyType: Any.Type = Optional.self
    anyType is OptionalProtocol.Type // true
    

提交回复
热议问题