5

I want to do something along those lines:

class MyClass {}
struct MyStruct {}

let newStruct = typeFromName("MyStruct").init()
let newClass = typeFromName("MyClass").init()

I would like to be able to load information from a config file that would allow me to create different classes or struct base on a string in that file.

Vincent Bernier
  • 8,534
  • 4
  • 32
  • 39
  • Not like this, without going down to ObjC (you can do this with `NSClassFromString` on `NSObject` subclasses). You will need to use a switch statement to do this in pure Swift. That's on purpose. You can't make this type safe based on strings. – Rob Napier Sep 23 '16 at 02:05
  • 1
    Thanks @RobNapier, I would like to stay away from NSObject (for learning Swift possibilities and limitations) Would it be possible to convert a string to a Type and make a conditional cast to the returned item? – Vincent Bernier Sep 23 '16 at 02:08
  • 1
    No. That still can't be compile-time type-checked. What is the static (at compile-time) type of `newStruct`? How can you prove that type has an `init()` method? ObjC is a wildly dynamic language that allows all kinds of runtime type manipulation. *Every* object in ObjC is an `id` and is dynamically allocated on the heap. Swift is a highly static language (with limited bridges into ObjC). You have to be able to type check things at compile time. Structs in particular do stack allocation. How many bytes are required to store `newStruct` on the stack? – Rob Napier Sep 23 '16 at 02:10
  • 2
    Thanks. I was afraid that it would not be possible. There is a lot to like from Swift, but coming from ObjC, the lack of dynamism of Swift can be annoying... from time to time. – Vincent Bernier Sep 23 '16 at 02:15
  • 1
    Another way of looking at it is that Objective-C allowed you to be lazy and to speak loosely. You should think whether there is a Swifty _way_ to accomplish what you want to accomplish. I have found that I don't miss Objective-C's dynamism at all any more. – matt Sep 23 '16 at 02:17
  • 2
    I have a swift implementation, that is working, but it is very ugly and very long. I know that the Objective-C version would be a lot shorter. So I'm trying to find a way to make it shorter and more elegant in Swift. – Vincent Bernier Sep 23 '16 at 02:27
  • My experience so far has been that the ObjC version is short as long as everything is as expected. When not…not so much crashes as "nothing happens" (nil messaging). Swift tends to force you at compile time to consider those edge cases. Annoying while writing, but beautiful when the bugs do not occur. (Not to say that dynamism never has its place; just much less frequently than I used to believe.) – Rob Napier Sep 23 '16 at 02:58
  • @VincentBernier what is your ugly and long solution? I'm very interested as I'm running into similar problems – joehinkle11 Dec 25 '19 at 20:23

0 Answers0