加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift – 检查变量是否为Optional,以及它包装的类型

发布时间:2020-12-14 05:44:39 所属栏目:百科 来源:网络整理
导读:是否可以检查变量是否是可选的,以及它包装的是什么类型? 可以检查变量是否是特定的可选: let someString: String? = "oneString"var anyThing: Any = someStringanyThing.dynamicType // Swift.OptionalSwift.StringanyThing.dynamicType is OptionalStrin
是否可以检查变量是否是可选的,以及它包装的是什么类型?

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

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

但是可以再次检查任何类型的可选项吗?就像是:

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

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

// hypothetical code 
anyThing.optionalType // returns String.Type
从 a protocol can be created as means of a typeless Optional开始,可以使用相同的协议来提供对可选类型的访问.示例在Swift 2中,尽管它在以前的版本中应该类似:
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
}

该协议甚至可以用于check and unwrap the contained optional value

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读