0

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"
7
  • Casting to Array<AnyObject> erases your types. You'll need to маке test a generic function. I'm working on my answer right now. BTW, Swift allows top level functions. It's preferable to static members in arbitrary classes like tester. This isn't Java ;) Commented Sep 28, 2016 at 17:28
  • @AlexanderMomchliov Awesome. I'll be waiting for your answer then. Haven't done much with the minimal swift reflection stuff. How did you know I was taught on java back in the day!? lol Commented Sep 28, 2016 at 17:34
  • Forcing static code that doesn't make any sense to be associated to a type to be associated to a type for the arbitrary pursuit of object orientation is a dead giveaway for Java :p Commented Sep 28, 2016 at 17:53
  • @AlexanderMomchliov Yeah. I kinda just slammed the playground together really quick for this question. Good catch. Commented Sep 28, 2016 at 17:55
  • @stevennorris I have an idea in mind for how to do this, but I can't quite figure it out yet. I"ll ask my own question on the matter, and see how it goes Commented Sep 28, 2016 at 18:20

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.