mardi 5 mai 2015

swift type comparison against class types

It's easy to do type comparison along the lines of:

if foo is NSDate { ... }

or

if let bar = foo as NSDate { ... }

but I haven't had any luck testing an object's type against a class type.

Here's a playground that shows what I've tried:

import UIKit

class DateRowType : NSObject {
    static var dataType : AnyClass {
        get {
            return NSDate.self
        }
    }
}

let date = NSDate()

// never succeeds
if reflect(date).valueType is DateRowType.dataType.Type {
    print ("it's a date!")
}

// prints error 'dataType' is not a member type of 'DateRowType'
if let newDate = date as DateRowType.dataType {
    print("it's a date!")
}


// string comparison failure due to NSDate class cluster
reflect(date).valueType // __NSDate
print(DateRowType.dataType) // NSDate

What is the correct way to do this? Am I returning the wrong type from dataType?





Aucun commentaire:

Enregistrer un commentaire