检查变量是否是可选的,以及它包装的类型 [英] Check if variable is an Optional, and what type it wraps

查看:26
本文介绍了检查变量是否是可选的,以及它包装的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以检查一个变量是否是可选的,以及它包装的是什么类型?

Is it possible to check if a variable is an optional, and what type is it wrapping?

可以检查变量是否是特定的可选变量:

It is possible to check if a variable is an specific optional:

let someString: String? = "oneString"
var anyThing: Any = someString

anyThing.dynamicType // Swift.Optional<Swift.String>
anyThing.dynamicType is Optional<String>.Type // true
anyThing.dynamicType is Optional<UIView>.Type // false

但是是否可以再次检查任何类型的可选?类似的东西:

But is it possible to check agains any type of optional? Something like:

anyThing.dynamicType is Optional.Type // fails since T cant be inferred
// or 
anyThing.dynamicType is Optional<Any>.Type // false

一旦知道你有一个可选的,检索它包装的类型:

And once knowing you have an optional, retrieve the type it is wrapping:

// hypothetical code 
anyThing.optionalType // returns String.Type

推荐答案

自从 可以通过无类型可选的方式创建协议,同样的协议可以用于提供对可选类型的访问.示例在 Swift 2 中,尽管它在以前的版本中应该类似:

Since a protocol can be created as means of a typeless Optional the same protocol can be used to provide access to the optional type. Example is in Swift 2, although it should work similarly in previous versions:

protocol OptionalProtocol {
    func wrappedType() -> Any.Type
}

extension Optional : OptionalProtocol {
    func wrappedType() -> Any.Type {
        return Wrapped.self
    }
}

let maybeInt: Any = Optional<Int>.Some(12)
let maybeString: Any = Optional<String>.Some("maybe")

if let optional = maybeInt as? OptionalProtocol {
    print(optional.wrappedType()) // Int
    optional.wrappedType() is Int.Type // true
}

if let optional = maybeString as? OptionalProtocol {
    print(optional.wrappedType()) // String
    optional.wrappedType() is String.Type // true
}

该协议甚至可以用于检查并解开包含的可选值

这篇关于检查变量是否是可选的,以及它包装的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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