Created
August 15, 2016 16:31
-
-
Save odlp/36f32a2101bc03fafaae54691569335c to your computer and use it in GitHub Desktop.
Swift Class name as a String
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//: 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" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Discovered the
String(AClass.self)
trick from this StackOverflow answer