Determine Object Type of Array Element Parameter

人走茶凉 提交于 2019-12-11 23:50:02

问题


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"

来源:https://stackoverflow.com/questions/39753881/determine-object-type-of-array-element-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!