How to create a swift object given the classname “EKAttendee”

北慕城南 提交于 2020-01-16 21:57:49

问题


Given the following objective c code

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

what would the swift code be?


回答1:


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)
}



回答2:


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()



回答3:


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


来源:https://stackoverflow.com/questions/35050308/how-to-create-a-swift-object-given-the-classname-ekattendee

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