Swift中,如果想在运行时判断一个对象的类型是不是可选类型,则可以使用Mirror,如下代码所示,所有的可选类型都将返回optional

let value: Int? = 3
Mirror(reflecting: value).displayStyle		// optional

MirrordisplayStyle属性的类型是Mirror.DisplayStyle,这是一个枚举类型,用于为Mirror的主体对象提供一种建议性的解析,其定义如下代码所示:

/// A suggestion of how a `Mirror`'s `subject` is to be interpreted.
///
/// Playgrounds and the debugger will show a representation similar
/// to the one used for instances of the kind indicated by the
/// `DisplayStyle` case name when the `Mirror` is used for display.
public enum DisplayStyle {

    case `struct`

    case `class`

    case `enum`

    case tuple

    case optional

    case collection

    case dictionary

    case set
}

枚举值范围之外的类型,其MirrordisplayStyle属性将返回nil,如下代码所示:

let value: Int = 20
Mirror(reflecting: value).displayStyle		// nil

let str: String = "30"
Mirror(reflecting: str).displayStyle		// nil