确定Any.Type是否为可选 [英] Determine if Any.Type is Optional

查看:140
本文介绍了确定Any.Type是否为可选的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试确定一个给定的类型是否是一个可选的类型 t Any.Type )我正在使用这个测试

  t是可选的< Any> .Type 
/ pre>

但它总是返回false。



那么有什么办法可以实现吗? >

解决方案

假设你想要做的是这样的:

  let anyType:Any.Type =可选< String> .self 
anyType是可选< Any> .Type // false
pre>

目前(从Swift 2开始)目前不幸的是不支持协方差或相反性,并直接对可选.Type 进行类型检查:

  //无法推断泛型参数Wrapped的参数
anyType是Optional.Type //导致错误

另一种方法是使可选扩展特定的协议,并检查该类型:

  protocol OptionalProtocol {} 

extension可选:OptionalProtocol {}

let anyType:Any.Type =可选< String> .self
anyType是OptionalProtocol.Type // true


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

t is Optional<Any>.Type

but it returns always false.

So is there any way to achieve this?

解决方案

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

let anyType: Any.Type = Optional<String>.self
anyType is Optional<Any>.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<String>.self
anyType is OptionalProtocol.Type // true

这篇关于确定Any.Type是否为可选的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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