Determine Object Type of Array Element Parameter

2019-09-05 15:54发布

问题:

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. Specifically, the element type doesn't come back proper due to casting.

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("ATYPE Good: ", 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"
"ATYPE Good:  Array<NSString>\n"
"ETYPE:  AnyObject\n"