-2

I know to find class type from class name we can do something as shown below or can use NSClassFromString. Can we do similar thing for structs, enums or any other data type?

guard let classType = Bundle.main.classNamed("AppName.ClassName") as? ClassName.Type else {
    print("Class Type not found")
    return
}

My question is similar to this one Swift language NSClassFromString . Only difference is I want to know can we do it for other data types as well like structs and enums.

creeperspeak
  • 5,403
  • 1
  • 17
  • 38
Subash thapa
  • 47
  • 1
  • 4
  • 1
    Does this answer your question? [Print Struct name in swift](https://stackoverflow.com/questions/35088970/print-struct-name-in-swift) – koen Mar 04 '20 at 23:05
  • @koen I don't want Struct's name from Struct. It's actually opposite. I have a structs name but I don't have struct itself to initialize it or access its static properties. – Subash thapa Mar 04 '20 at 23:13
  • Swift is all about safety, so you cannot evaluate/instantiate a struct from string at runtime. – yo1995 Apr 26 '22 at 00:06

1 Answers1

2

can we do it for other data types as well like structs and enums

No, you can't. NSClassFromString is an NSObject feature; it belongs to Cocoa and the Objective-C world. There's no way in Swift to go from a string to a reference to a type; it's not that kind of language.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • My question is not that we can use NSClassFromString in Swift or not. Actually we can use it in swift as well. My question is that is there anything similar to it get reference to other data types? Any ways thanks for the response. – Subash thapa Mar 05 '20 at 19:32
  • No, you can't actually use it "in Swift". Try it in a playground in which you do _not_ `import Foundation` or `import UIKit`. You will find it doesn't even compile. It is not a Swift feature _at all_. Do you understand now? And my answer still stands: "No". – matt Mar 05 '20 at 19:37
  • Ok I was not asking about pure swift.May be there was a communication gap. It's completely ok for me if I can achieve the result by using objective c features and capabilities in Swift. – Subash thapa Mar 05 '20 at 19:44
  • Well, you can't. My answer stands. – matt Mar 06 '20 at 16:31