0

Given the following objective c code

Class className = NSClassFromString(@"EKAttendee");
id attendee = [className new];

what would the swift code be?

Keith John Hutchison
  • 4,955
  • 11
  • 46
  • 64

3 Answers3

0

Here is a simple example that shows how to use NSClassFromString:

if let clazz = NSClassFromString("NSView") as? NSView.Type {
    let v = clazz.init(frame: NSRect(x: 0, y: 0, width: 100, height: 100))
    print(v.frame) // (0.0, 0.0, 100.0, 100.0)
}
Stefan Arentz
  • 34,311
  • 8
  • 67
  • 88
0

Try https://objectivec2swift.com/#/converter/code

I copied this into it

Class className = NSClassFromString(@"EKAttendee");
id attendee = [className new];

and I got back this

var className: AnyClass = NSClassFromString("EKAttendee")
var attendee: AnyObject = className()
Alan Perez
  • 186
  • 4
0

This worked.

let anyObjectType : AnyObject.Type = NSClassFromString("EKAttendee")!
let nsObjectType : NSObject.Type = anyObjectType as! NSObject.Type
var attendee: AnyObject = nsObjectType.init() 

print("\(attendee)") 

Results

EKAttendee <0x51763530>
email               : (null)
isCurrentUser       : 0
replyRequested      : 0
role                : (null)
status              : (null)
type                : 0
scheduleForceSend   : 0
Keith John Hutchison
  • 4,955
  • 11
  • 46
  • 64