Xcode 7 Beta 4 is out and it is a doozy! One of the changes is that performSelector
is now available from Swift. Now, this isn't going to make your Swift types dynamic all of a sudden. However, what it does open the door for, is writing both your ObjC-style code and your Swift code all in the same language: Swift.
That's huge.
Here's some really ugly code to demonstrate:
@objc (Foo)
class Foo : NSObject {
func bar() -> String {
return "bar"
}
}
let foo = Foo()
let value = foo.performSelector(Selector("bar")).takeUnretainedValue()
let result = value as? String
print("result: \(result)")
if let c = NSClassFromString("Foo") {
let newFoo = c.alloc().performSelector(Selector("init")).takeUnretainedValue() as? Foo
print("newFoo: \(newFoo?.bar())")
}
I'm actually pretty excited by this. This is another step closer, in my opinion, for winning in the pragmatic realm. There are certain types of problems (like a plug-in architecture) that are suited to this type of dynamic invocation.
This seems like baby steps to a great merging of the two worlds.
Update: July 23rd
It turns out, this is possible without using @objc
as well:
class Bar : CustomStringConvertible {
required init() {}
var description: String { return "hahaha" }
}
if let c = NSClassFromString("PerformSelector.Bar") as? Bar.Type {
let i = c.init()
print("interesting: \(i)")
}
Just update "PerformSelector" to your module name, and voilà! For generic classes, you need to use it fist before it gets registered.
Good stuff!