I am aware of this question regarding how we can get a readable class name of an objective-c class in Swift.
What I want to achieve is getting the readable class name of a Swift class from inside objective-c without mangling the class name with the module.
So if I have a Swift class:
class Foo: NSObject{}
Then inside Objective-C I would love to use the convenient NSStringFromClass to convert the class name to a string.
I would expect NSStringFromClass([Foo class])
to return @"Foo"
but instead it returns @"Bar.Foo"
withBar
being the module name.
I came across this Gist but it seems a little hacky and messy, is there a better way? Something that doesn't include typing the class name manually into a string would be preferred.
Just put @objc(YourClassName)
in your swift class:
@objc(YourClassName)
class YourClassName: NSObject {
}
And you can use NSStringFromClass like this:
NSStringFromClass(YourClassName.self)
It should also work from Objective-C then.
With Swift 2.1 a comment to this answer states that this is sufficient:
class YourClassName: NSObject {
}
And just use:
var str = String(YourClassName)
I have not tested this from Objective-C code myself though.
There's been a edit-suggestions that want to use this instead for Swift 4:
var str = String(describing: YourClassName.self)
I've not tested this from Objective-C though.