Swift: check type of property from object (Reflection)

Urkman

I want to use reflection to check the property type of a given object at runtime.

I use this code:

//: Playground - noun: a place where people can play
import UIKit

class Object: NSObject
{
    var type:Int?
    var name="Apple"
    var delicious=true
}

let object = Object()

// now check the "type" property
println(reflect(object)[1].1.value) // this gives me nil
println(reflect(object)[1].1.valueType) // this gives Swift.Optional<Swift.Int>

// check for Optional... works fine - Says "Optional"
if reflect(object)[1].1.disposition == MirrorDisposition.Optional {
    println("Optional")
}

// check for type... does not work, because type is an optional - says: not Int
if reflect(object)[1].1.valueType is Int.Type {
    println("Int")
} else {
    println("no Int")
}

As you can see on this code, I can'n check "valueType", because it is an Optional.

But how can I check the type of this "Optional" property?

Thanks, Urkman

Zell B.

Note that optional Int is a different type from Int so you must check it with Int?.Type

if reflect(object)[1].1.valueType is Int?.Type {
    println("Int Optional")
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Kotlin Reflection - Check if property has type

Swift check type of object

Set property type based on reflection of another object

Kotlin Reflection check if class property is ArrayList of specific type

How can I find the type of a property dynamically in swift (Reflection/Mirror)?

Getting property type with reflection

Using Scala reflection to check for a method on an object or to find key type on a Map

check if any property in an object is nil - Swift 3

swift check an object's property existence

Check if an object has a property of a certain type

Reflection API (Type of an object)

Dynamically check an object type in Swift 2

Check Data type for a serialized object in Swift

How to check is property right from interface type?

Get property from object and check if it contains value

Unable to access Swift 4 class from Objective-C: "Property not found on object of type"

Assign to Property of Type Using Reflection

How to get the properties from a dynamic (Anonymous Type) object using reflection?

Get type of primitive field from an object using Scala reflection

How to cast a object get from reflection to DbSet<type>

Set object property using reflection

Swift: Pass type from property to generic function

Reflection from Java to Swift

How to find a property type from javascript object?

property does not exists on type Object from subscribe

Typescript get object property type from name

Typescript object property from type definiton

Setting the type of variable from an object property

Infering type of object from value of property in Typescript