Pebble Coding

ソフトウェアエンジニアによるIT技術、数学の備忘録

swift Reflectableプロトコル

Reflectableプロトコルとは、型情報を扱うためのものと考えて良い。

protocol Reflectable {
    func getMirror() -> MirrorType
}

protocol MirrorType {
    var value: Any { get }
    var valueType: Any.Type { get }
    var objectIdentifier: ObjectIdentifier? { get }
    var count: Int { get }
    subscript (i: Int) -> (String, MirrorType) { get }
    var summary: String { get }
    var quickLookObject: QuickLookObject? { get }
    var disposition: MirrorDisposition { get }
}

enum MirrorDisposition {
    case Struct
    case Class
    case Enum
    case Tuple
    case Aggregate
    case IndexContainer
    case KeyContainer
    case MembershipContainer
    case Container
    case Optional
    case ObjCObject
}

enum QuickLookObject {
    case Text(String)
    case Int(Int64)
    case UInt(UInt64)
    case Float(Float32)
    case Double(Float64)
    case Image(Any)
    case Sound(Any)
    case Color(Any)
    case BezierPath(Any)
    case AttributedString(Any)
    case Rectangle(Float64, Float64, Float64, Float64)
    case Point(Float64, Float64)
    case Size(Float64, Float64)
    case Logical(Bool)
    case Range(UInt64, UInt64)
    case View(Any)
    case Sprite(Any)
    case URL(String)
}

is演算子というものがあるがこれも、型を判定するのに使える。

var a:String = "some" 
if a is String {
    println("a is string ")
} else {
    println("a is not string")
}
if a is Int {
    println("a is Int")
} else {
    println("a is not Int")
}
// a is string 
// a is not Int
var a:String = "some" 
let m = a.getMirror()
println("value \(m.value)")
println("valueType \(m.valueType)")
println("objectIdentifier \(m.objectIdentifier)")
println("count \(m.count)")
println("summary \(m.summary)")
println("quickLookObject \(m.quickLookObject)")
println("disposition \(m.disposition)")
// value some
// valueType Swift.String
// objectIdentifier nil
// count 0
// summary some
// quickLookObject Optional((Enum Value))
// disposition (Enum Value)

型情報を扱うプログラミングをしたいときにしか使わないと考えて良い。

参考 Simple Reflection in Swift