是否可以将Any强制转换为Optional? [英] Is it possible to cast Any to an Optional?

查看:79
本文介绍了是否可以将Any强制转换为Optional?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一段这样的代码:

Let's say I have a piece of code like this:

let x: Int? = 10  
let y: Any = x

现在我想将y强制转换为Int吗?:

Now I want to cast y to Int?:

let z = y as Int? // Error: Cannot downcast from 'Any' to a more optional type 'Int?'

这是不可能还是有其他方法吗?

Is this just not possible or is there another way?

推荐答案

对于Swift 2.0,您可以使用以下代码:

For Swift 2.0, you can use the following:

let x: Int? = 10
let y: Any = x
let z = Mirror(reflecting: y).descendant("Some") as? Int

或作为功能:

func castToOptional<T>(x: Any) -> T? {
    return Mirror(reflecting: x).descendant("Some") as? T
}
let x: Int? = 10
let y: Any = x
let z: Int? = castToOptional(y)

或者,如果您不喜欢反射,也可以这样做:

Or you can do this if you don't like Reflection:

func castToOptional<T>(x: Any) -> T {
    return x as! T
}
let x: Int? = 10
let y: Any = x
let z: Int? = castToOptional(y)

这篇关于是否可以将Any强制转换为Optional?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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