mercredi 28 septembre 2016

Reflection To Determine Object Type of Parameter

Put a playground below that shows my issue and it's output. I need to write a method you can pass AnyObject? into, then determine the type of that object. If it's an array, I'll also need to determine it's Element type. This works fine before the method is called, but after I can't get at the types.

Playground

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

import UIKit
import Foundation

extension Array {
    var ElementType: Element.Type {
        return Element.self
    }
}

class tester {
    static func test(array:AnyObject?){
        print("ATYPE: ", array.dynamicType)
        print("ETYPE: ", (array as! Array<AnyObject>).ElementType)
    }
}

let myArray: Array<NSString> = []
print("ATYPE ORIG: ", myArray.dynamicType)
print("ETYPE ORIG: ", myArray.ElementType)
tester.test(myArray)

Output

"ATYPE ORIG:  Array<NSString>\n"
"ETYPE ORIG:  NSString\n"

"ATYPE:  Optional<AnyObject>\n"
"ETYPE:  AnyObject\n"





Aucun commentaire:

Enregistrer un commentaire