How to check the type of a variable against another variable in Swift -
i have array of classes, , want check if variable matches element in array. in objective-c:
nsarray *arrayofclasses = @[uibutton.class, uilabel.class]; class aclass = arrayofclasses[0]; uibutton *button = [uibutton new]; if ([button iskindofclass:aclass]) { nslog("button aclass") } but can't figure out way in swift:
let arrayofclasses = [uibutton.self, uilabel.self] let aclass = arrayofclasses[0] as! nsobject.type let button = uibutton() if button aclass { nslog("button aclass") } the code above throws error saying 'aclass' not type. i've tried as! anyclass, as! anyclass.type, as! anyobject.type, etc.
updated: @matt, know how work in pure swift. if arrayofclasses created in objective-c, crashes error could not cast value of type 'dummya' (0x1049f48a0) 'swift.anyobject.type'. make sense, because objective-c class anyobject in swift, , can't convert anyobject anyclass.
here's sample code:
@interface dummya : nsobject + (nsarray *)dummies; @end @interface dummyb : nsobject @end @implementation dummya + (nsarray *)dummies { return @[[dummya class], [dummya class], [dummyb class], [dummyb class]]; } @end @implementation dummyb @end let arrayofclasses = dummya.dummies() let aclass: anyclass = arrayofclasses[0] as! anyclass // crash! i found way make work, looks weird right way!
let aclass = nsclassfromstring( nsstringfromclass( object_getclass(arrayofclasses[0]) )) // aclass (anyclass!) $r0 = dummya
tricky, isn't it? think it:
let arrayofclasses : [anyclass] = [uibutton.self, uilabel.self] let aclass : anyclass = arrayofclasses[0] let button = uibutton() let ok = button.dynamictype === aclass // true line 1: if don't declare type of arrayofclasses explicitly, implicit array of anyobject, , that's going give trouble later because anyobject can't class.
line 2: aclass implicitly anyclass, right, need explicit typing quiet warning compiler.
line 3: no problem there.
line 4: well, have know way ask whether 1 thing's type given type. class of button, class object, dynamictype, can ask, same class object whatever class object aclass is.
edit: you've edited question array of classes comes objective-c, don't see how changes anything:
let arrayofclasses = dummya.dummies() let aclass : anyobject = arrayofclasses[0] let button = uibutton() let ok = button.dynamictype === aclass.self
Comments
Post a Comment