如何在Swift中检查类型是否为Optional? [英] How can you check if a type is Optional in Swift?

查看:139
本文介绍了如何在Swift中检查类型是否为Optional?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检查Swift中的类型是否为Optional?

How can you check if a type is Optional in Swift?

说我有一个PartialKeyPath类型的变量,其中:

Say I have a variable of type PartialKeyPath where:

struct Foo {
    let bar: String
    let baz: String?
}

typealias Property<Root> = (key: PartialKeyPath<Root>, value: Any?)
typealias Properties<Root> = [Property<Root>]

现在说我遍历Properties的一个实例:

Now say I iterate thru an instance of Properties:

properties.forEach { prop in
    let valueType1 = type(of: prop.key).valueType
    let valueType2 = type(of: value)

    ...

如何在这里检查valueType1是否为Optional<valueType2>,或者对于其他任何类型,它是否为Optional?

How can I check here whether valueType1 is Optional<valueType2>, or whether it is Optional of any other flavor for that matter?

到目前为止,我发现的唯一方法确实很丑...

So far the only way I’ve found is really ugly...

推荐答案

这是一个骇人但有效的解决方案:

This is a hacky but working solution:

func isOptional(_ type: Any.Type) -> Bool {
    let typeName = String(describing: type)
    return typeName.hasPrefix("Optional<")
}

测试:

let t1 = Int?.self
let t2 = Bool.self

print(isOptional(t1))
// true

print(isOptional(t2))
// false

这篇关于如何在Swift中检查类型是否为Optional?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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