Skip to content

Instantly share code, notes, and snippets.

@odlp
Created August 15, 2016 16:31
Show Gist options
  • Save odlp/36f32a2101bc03fafaae54691569335c to your computer and use it in GitHub Desktop.
Save odlp/36f32a2101bc03fafaae54691569335c to your computer and use it in GitHub Desktop.
Swift Class name as a String
//: Playground - noun: a place where people can play
import UIKit
// Option 1 ---------------------------
protocol DescribeableClass {
static func className() -> String
}
extension DescribeableClass {
static func className() -> String {
return String(self.self)
}
}
class Thing: DescribeableClass {
}
Thing.className() // => "Thing"
// Option 2 ---------------------------
class AnotherThing {
static let name = {
return String(AnotherThing.self)
}()
}
AnotherThing.name // => "AnotherThing"
// Option 3 ---------------------------
func nameOfClass(subject: AnyClass) -> String {
return String(subject.self)
}
class YetAnotherThing {
}
nameOfClass(YetAnotherThing) // => "YetAnotherThing"
@odlp
Copy link
Author

odlp commented Aug 15, 2016

Discovered the String(AClass.self) trick from this StackOverflow answer

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment