gpt4 book ai didi

swift - 检查变量是否是可选的,以及它包装的类型

转载 作者:IT王子 更新时间:2023-10-29 05:23:41 25 4
gpt4 key购买 nike

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

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

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可以使用相同的协议(protocol)来提供对可选类型的访问。示例在 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
}

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

关于swift - 检查变量是否是可选的,以及它包装的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32645612/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com