0

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.

3
  • 1
    Does this answer your question? Print Struct name in swift Commented Mar 4, 2020 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. Commented Mar 4, 2020 at 23:13
  • Swift is all about safety, so you cannot evaluate/instantiate a struct from string at runtime. Commented Apr 26, 2022 at 0:06

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

6 Comments

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.
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".
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.
Well, you can't. My answer stands.
@meaning-matters Why would it? As I said in my answer, this would be completely contradictory to the spirit of Swift.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.