Re: How to get the class name in Swift?
Re: How to get the class name in Swift?
- Subject: Re: How to get the class name in Swift?
- From: "Gerriet M. Denkmann" <email@hidden>
- Date: Wed, 30 Jul 2014 16:01:34 +0700
On 30 Jul 2014, at 14:59, Quincey Morris <email@hidden> wrote:
> On Jul 30, 2014, at 00:02 , Gerriet M. Denkmann <email@hidden> wrote:
>
>> How to translate this:
>> NSString *className = [ [ someObject class ] description ];
>> into Swift?
>
> AFAICT, there isn’t any equivalent mechanism built into Swift yet. The two best answers I could find:
>
> 1. (from StackOverflow) Use NSStringFromClass (someObject.dynamicType), though this gives a mangled class name.
>
> 2. (from an example in the Swift book) Write a class method in each class you want to inspect, that returns a string literal for the readable class name. You can put the name of this method in a protocol to which each such class would conform.
Method 2 does not work very well for system classes.
This seems to work:
extension NSObject // niceClassName
{
var niceClassName : String
{
let a = NSStringFromClass(self.dynamicType)
if a.hasPrefix("_") // ugly mangled name
{
let b = a as NSString
let range = b.rangeOfString("20")
if range.location == NSNotFound // strange class
{
return a
}
else // Swift class
{
let g = NSMaxRange(range)
let c = b.substringFromIndex( g )
let d = c as String
let h = countElements(d)
if h == 0 // strange class
{
return a
}
else // Swift class
{
return c
}
}
}
else // nice subclass of NSObject
{
return a
}
}
}
Thanks for your help!
Kind regards,
Gerriet.
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Xcode-users mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden